Cannot assign the first row as header in a CSV file

The code to read the CSV file:

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

Error:

KeyError: 'value'

The CSV file:

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

Upvotes: 0

Views: 117

Answers (1)

user2285236
user2285236

Reputation:

Your CSV file has extra whitespaces after the commas. You can pass skipinitialspace=True while reading the file.

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

Upvotes: 2

Related Questions