Reputation: 1
Here is my code-
import pandas as pd
df5=pd.read_csv(r'C:\Anaconda3\airtravel.csv')
print(df5)
Month "1958" "1959" "1960"
0 JAN 340 360 417
1 FEB 318 342 391
2 MAR 362 406 419
3 APR 348 396 461
4 MAY 363 420 472
5 JUN 435 472 535
6 JUL 491 548 622
7 AUG 505 559 606
8 SEP 404 463 508
9 OCT 359 407 461
10 NOV 310 362 390
11 DEC 337 405 432
But when I try to access this:-
print(df5['1960'])
I get an error.
KeyError: '1960'
I can't understand why is that happening. File link: https://people.sc.fsu.edu/~jburkardt/data/csv/csv.html
Thanks
Upvotes: 0
Views: 1164
Reputation: 1875
I've checked this file. We have two problems here. In the column names there is a space at the beginning and "" between the years.
Possible solutions:
Put a parameter 'skipinitialspace'. It will remove spaces and quatation marks. Then you can print it like you wanted:
df5 = pd.read_csv(r'C:\Anaconda3\airtravel.csv', skipinitialspace=True)
print(df5['1960'])
Remove spaces on both sides and add "" to the name:
df5 = pd.read_csv(r'C:\Anaconda3\airtravel.csv')
df5.columns = [x.strip() for x in df5.columns]
print(df5['"1960"'])
Leave it at it is and add space at the beginning:
df5 = pd.read_csv(r'C:\Anaconda3\airtravel.csv')
print(df5[' "1960"'])
Upvotes: 0
Reputation: 152
Your column includes quotations along with the column name. maybe df5['"1960"']
would work
Upvotes: 1