Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
381 views
in Technique[技术] by (71.8m points)

python - accessing the column in pandas in different way

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It looks like there is some unwanted character in the column name. Maybe is something like 'Economics ' or something else.

df.get('Economics') in that case would not give KeyError, instead it would just return nothing.

Try checking the output of df.columns and the length of the column name with len(df.columns[1]) .


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...