读取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
答案 0 :(得分: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