0

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

1
  • 1
    do df5.columns to see what the column name is, but, based on your sample data, it looks like it should be df5[' "1960"'] Commented Jan 28, 2021 at 16:41

2 Answers 2

1

Your column includes quotations along with the column name. maybe df5['"1960"'] would work

Sign up to request clarification or add additional context in comments.

Comments

0

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"'])
    

1 Comment

Thank you very much. That works. I also removed the spaces from the original file and was able to print it as df5['1960']. So I guess print(df5['1960']) will only work if there would be no spaces.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.