Pandasでcsvファイルを読み込む方法

投稿者: | 2020年11月2日

Pandasでcsvファイルを読み込む方法です

CSVファイル

1,2,3,4,5,6,7,8,9,10
1,2,3,4,5,6,7,8,9,10
1,2,3,4,5,6,7,8,9,10
1,2,3,4,5,6,7,8,9,10
1,2,3,4,5,6,7,8,9,10
1,2,3,4,5,6,7,8,9,10
1,2,3,4,5,6,7,8,9,10
1,2,3,4,5,6,7,8,9,10
1,2,3,4,5,6,7,8,9,10
1,2,3,4,5,6,7,8,9,10

1行目をヘッダーとして読み込む場合

import pandas as pd

file = r'CSVファイルのパス'
df = pd.read_csv(file)
print(df)
print(df.columns)

結果

   1  2  3  4  5  6  7  8  9  10
0  1  2  3  4  5  6  7  8  9  10
1  1  2  3  4  5  6  7  8  9  10
2  1  2  3  4  5  6  7  8  9  10
3  1  2  3  4  5  6  7  8  9  10
4  1  2  3  4  5  6  7  8  9  10
5  1  2  3  4  5  6  7  8  9  10
6  1  2  3  4  5  6  7  8  9  10
7  1  2  3  4  5  6  7  8  9  10
8  1  2  3  4  5  6  7  8  9  10
Index(['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'], dtype='object')

1行目をヘッダーとして読み込まない場合

import pandas as pd

file = r'csvファイルのパス'
df = pd.read_csv(file, header=None)
print(df)
print(df.columns)

結果

   0  1  2  3  4  5  6  7  8   9
0  1  2  3  4  5  6  7  8  9  10
1  1  2  3  4  5  6  7  8  9  10
2  1  2  3  4  5  6  7  8  9  10
3  1  2  3  4  5  6  7  8  9  10
4  1  2  3  4  5  6  7  8  9  10
5  1  2  3  4  5  6  7  8  9  10
6  1  2  3  4  5  6  7  8  9  10
7  1  2  3  4  5  6  7  8  9  10
8  1  2  3  4  5  6  7  8  9  10
9  1  2  3  4  5  6  7  8  9  10
Int64Index([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype='int64')

任意のヘッダーを付与する場合

import pandas as pd

file = r'csvファイルのパス'
df = pd.read_csv(file, header=None, names=('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'))
print(df)
print(df.columns)

結果

   a  b  c  d  e  f  g  h  i   j
0  1  2  3  4  5  6  7  8  9  10
1  1  2  3  4  5  6  7  8  9  10
2  1  2  3  4  5  6  7  8  9  10
3  1  2  3  4  5  6  7  8  9  10
4  1  2  3  4  5  6  7  8  9  10
5  1  2  3  4  5  6  7  8  9  10
6  1  2  3  4  5  6  7  8  9  10
7  1  2  3  4  5  6  7  8  9  10
8  1  2  3  4  5  6  7  8  9  10
9  1  2  3  4  5  6  7  8  9  10
Index(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'], dtype='object')