Skip to content
Advertisement

How to correctly read specific csv column

Hey everyone my question is kinda silly but i am new to python) I am writing a python script for c# aplication and i got kinda strange issue when i work with csv document.

When i open it it and work with Date column it works fine

df=pd.read_csv("../Debug/StockHistoryData.csv")
df = df[['Date']]

But when i try to work with another columns it throws error

df = df[['Close/Last']] 

KeyError: “None of [Index([‘Close/Last’], dtype=’object’)] are in the [columns]”

It says there are no such Index but but when i print the whole table it works fine and shows all columns

Table Image Error image

Advertisement

Answer

Take a look at the first row of your CSV file. It contains colum names (comma-separated). From time to time it happens that this initial line contains a space after each comma. For a human being it is quite readable and even intuitive. But read_csv adds these spaces to column names, what is sometimes difficult to discover.

Another option is to run print(df.columns) after you read your file. Then look for any extra spaces in column names.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement