Skip to main content

Reading CSV Files with pandas

·476 words
icysamon
Author
icysamon
I really love making things by hand and turning my ideas into reality.

Basic Operations
#

Import pandas.

import pandas as pd

Read the CSV file.

df = pd.read_csv('example.csv')
Important
  • If there is no header, use pd.read_csv(example.csv, header=None).
  • If the file contents have changed, you must reload the file using pd.read_csv().

Print the contents of the CSV file.

print(df)

The output will look like this.

     A  B  C  D  E  F  G  H  I   J   K   L   M   N   O   P   Q   R   S   T   U   V   W   X   Y   Z
0    1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26
1    1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26
2    1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26
3    1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26
4    1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26
..  .. .. .. .. .. .. .. .. ..  ..  ..  ..  ..  ..  ..  ..  ..  ..  ..  ..  ..  ..  ..  ..  ..  ..
195  1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26
196  1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26
197  1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26
198  1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26
199  1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26

Row Operations
#

Retrieve the first 10 rows
#

print(df.head(10))

Retrieve the last 10 rows
#

print(df.tail(10))

Retrieve specified rows
#

print(df[64:89])

Set the maximum number of rows to display
#

pd.set_option('display.max_rows', 100)

or

pd.set_option('display.max_rows', None)
Important

After changing the setting, you must reload the file using pd.read_csv().

Column Operations
#

Retrieve Specified Columns
#

print(df[['A', 'P']])

Or

print(df.iloc[:,4:6])

Retrieve Rows Where the Value in Column A Is Greater Than 0
#

print(df[df.A > 0])

Set the maximum number of columns to display
#

pd.set_option('display.max_columns', 100)

Or

pd.set_option('display.max_columns', None)
Important

After changing the settings, you must reload the file using pd.read_csv().