我使用pandas从数据框中提取两列,但是一列变为索引,然后在尝试访问该列时出现密钥错误

时间:2017-10-03 19:33:28

标签: python pandas dataframe

df.columns = df.columns.str.strip() ##found a fix for leading whitespaces
arrest_only_Y= df.loc[df['ARREST'] == 'Y']
arrest_only_Y_two_col=arrest_only_Y[["ARREST",'LOCATION DESCRIPTION','CASE#']]##running fine here 
arrest_only_Y_two_col.reset_index()
arrest_only_Y_two_col_groupby = arrest_only_Y_two_col.groupby('LOCATION DESCRIPTION').count() ##and here as well ## arrest_only_Y_two_col_groupby_desc=arrest_only_Y_two_col_groupby.sort_values(['ARREST'],ascending = False).head()
arrest_only_Y_two_col_groupby_desc.reset_index(drop = True)
arrest_only_Y_two_col_groupby_desc

在输出中LOCATION DESCRIPTION变为索引,我无法将其用作运行此代码的列

 locdesc_list = arrest_only_Y_two_col_groupby_desc['LOCATION 
 DESCRIPTION'].tolist()

我得到:Key Error : 'LOCATION DESCRIPTION'

2 个答案:

答案 0 :(得分:2)

替换你的行:

arrest_only_Y_two_col_groupby_desc.reset_index(drop=True)

使用:

arrest_only_Y_two_col_groupby_desc.reset_index(inplace=True)

答案 1 :(得分:1)

你可以尝试这个

df =pd.DataFrame(df,index=index,column=['A','B'])