2016-12-10 54 views
0

的代碼讀取CSV文件:無法分配的第一行作爲標題的CSV文件

import pandas as pd 
l = pd.read_csv('ex.csv', header=0, sep=',') 
print(l) 
pivoted = l.pivot('date', 'item', 'value') 

錯誤:

KeyError: 'value'

CSV文件:

date, item, value 
0, 1959-03-31 00:00:00, realgdp, 2710.349 
1, 1959-03-31 00:00:00, infl, 0.000 
2, 1959-03-31 00:00:00, unemp, 5.800 
3, 1959-06-30 00:00:00, realgdp, 2778.801 
4, 1959-06-30 00:00:00, infl, 2.340 
5, 1959-06-30 00:00:00, unemp, 5.100 
6, 1959-09-30 00:00:00, realgdp, 2775.488 
7, 1959-09-30 00:00:00, infl, 2.740 
8, 1959-09-30 00:00:00, unemp, 5.300 
9, 1959-12-31 00:00:00, realgdp, 2785.204 

回答

2

你CSV文件在逗號後有多餘的空格。讀取文件時,您可以通過skipinitialspace=True

s = ''' 
date, item, value 
0, 1959-03-31 00:00:00, realgdp, 2710.349 
1, 1959-03-31 00:00:00, infl, 0.000 
2, 1959-03-31 00:00:00, unemp, 5.800 
3, 1959-06-30 00:00:00, realgdp, 2778.801 
4, 1959-06-30 00:00:00, infl, 2.340 
5, 1959-06-30 00:00:00, unemp, 5.100 
6, 1959-09-30 00:00:00, realgdp, 2775.488 
7, 1959-09-30 00:00:00, infl, 2.740 
8, 1959-09-30 00:00:00, unemp, 5.300 
9, 1959-12-31 00:00:00, realgdp, 2785.204 
''' 

import io 
df = pd.read_csv(io.StringIO(s), skipinitialspace=True) 
# You'll need to pass the filename 
# df = pd.read_csv('ex.csv', skipinitialspace=True) 
df.pivot('date', 'item', 'value') 
Out: 
item     infl realgdp unemp 
date          
1959-03-31 00:00:00 0.00 2710.349 5.8 
1959-06-30 00:00:00 2.34 2778.801 5.1 
1959-09-30 00:00:00 2.74 2775.488 5.3 
1959-12-31 00:00:00 NaN 2785.204 NaN 
相關問題