pandas "groupby" 在 headers 中制作了一个无法访问或删除的关卡

pandas "groupby" produced a level in headers that is unable to access or delete

df_india = pd.read_csv('fakepath\file.csv')

df_india.head()

清理后数据框如下所示

df_india.head(5)

因为我想按州分组

df_india = df_india.groupby(by=['State']).sum()
df_india.head(5)

Here comes the unnecessary level, but i am unable to access or remove the 'State' level. I want both the columns on the same level as headers for the dataFrame

我尝试重置索引,然后 headers 看起来像一个级别 headers。

df_india.reset_index().head(2)

但仍然无法访问'State'列

df_india['State']

只需在 groupby() 方法中使用 as_index 参数并将其设置为等于 False:-

df_india = df_india.groupby(by=['State'],as_index=False).sum()

现在写:-

df_india['State']

使用reset_index()

时需要重新分配dataframe
df = df_india.reset_index()

或者您可以在调用 reset_index()

时使用 inplace=True
df_india.reset_index(inplace=True)