python - 分组和聚合后未找到 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
未找到的关键错误。
解决方案
在 groupby...pandas 之后,将 groupby 列放入索引中。在 pandas 中执行 groupby 后始终重置索引,不要执行drop=True
.
在你的代码之后。
df = df.reset_index()
然后您将获得所需的列。
推荐阅读
- android - ViewPager 图像视图在回收站视图中的随机项目位置显示 null
- ruby-on-rails - Rails 本地化:以扁平的非嵌套方式排列 i18n yml 文本有什么缺点吗?
- firebase - admin sdk 的 firebase 实时数据库规则
- vuetify.js - 深色主题不适用于所有子组件
- html - 从 CSS 关闭汉堡菜单
- php - php中多维数组的唯一数组
- c# - c# 沿弧线移动点
- flutter - 用颤振连接到沙发底座
- django - 显示一个表单域,即模板django中表单的一个选择域
- mongodb - 无法识别的管道阶段名称:'$unwind'