首页 > 解决方案 > 分组和聚合后未找到 Pandas colnames

问题描述

这是我的数据

threats = pd.read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020-08-18/threats.csv', index_col = 0)

这是我的代码 -

df = (threats
.query('threatened>0')
.groupby(['continent', 'threat_type'])
.agg({'threatened':'size'}))

然而df.columns 只是Index(['threatened'], dtype='object')结果。也就是说,只有受威胁的列不显示我实际按大陆和威胁类型分组的列,尽管存在于我的数据框中。

我想对我的数据框的大陆列执行操作,但它没有显示为列之一。例如 - continents = df.continent.unique()。这个命令给了我一个continent未找到的关键错误。

标签: pythonpython-3.xpandas

解决方案


在 groupby...pandas 之后,将 groupby 列放入索引中。在 pandas 中执行 groupby 后始终重置索引,不要执行drop=True.

在你的代码之后。

df = df.reset_index()

然后您将获得所需的列。


推荐阅读