I had a data set that looks like:
Id Economics English History Literature
0 56 1 1 2 1
1 11 1 0 0 1
2 6 0 1 1 0
3 43 2 0 1 1
4 14 0 1 1 0
I created this dataset by reading some csv from file, I could very easily accessed the columns just with df['Economics'], for example. Then I save it into the file with:
df.to_csv(file_path, sep=' ')
But when I reopen the dataset in other function for work i other purposes, and tried to access the columns in the same way, i.e.
df=pd.read_csv(file_path, sep=' ')
print df['Economics']
I've got
KeyError: Economics
I tried multiple encoding while reading, and also verified if it's not a multi-index dataframe, but everything was OK with encoding and index. I found out that there are another method: df.get('Economocs'), that, in this case worked without error. But, then, if I wanted iterated over the columns name, looking for 'Economics', again,I had an KeyError.
So my question: Why it happens? why sometimes I can access column directly with df['column_name'] and sometimes I need to use df.get('column_name'). And how to deal with column.names, in the case if the first method doesn't work?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…