重设索引不重设双groupby后的索引

2024-06-06 17:11:08 发布

您现在位置:Python中文网/ 问答频道 /正文

当我使用pandas groupby对一个值按组求和,并使用另一个groupby中的结果计算每个子组中组总数的百分比时,我无法重置索引以通过切片访问列。如何访问列或重置索引?你知道吗

test = pd.DataFrame({'Animal' : ['Falcon', 'Falcon','Parrot', 'Parrot','Mouse','Mouse'],'Type':['Bird', 'Bird', 'Bird', 'Bird', 'Rodent','Rodent'],'Count' : [380., 370., 24., 26., 1.9, 2.8]})

# second groupby gives a proportion of total animal counts within each type
gb = test.groupby(['Type','Animal']).sum().groupby(level=0).apply(lambda x: x / float(x.sum()))

取消堆栈时,无法重置索引以便提取列

gb = gb.unstack().reset_index()
gb.loc['Animal']

导致错误,表明没有名为“Animal”的列。你知道吗

如何在取消堆叠后重新设置,以便可以对列进行子集设置(或者重命名它们,这将是一个合适的替代项)?你知道吗

  • 编辑示例df以更清楚地说明问题

Tags: testpandastype重置parrotsumfalcongroupby
3条回答

你知道怎么计算吗?你知道吗

我认为第二个groupby操作不合适:

gb = test.groupby('Animal').sum().groupby(level=0).apply(lambda x: x / float(x.sum()))

试试这个:

gb = test.groupby("Animal").sum().apply(lambda x: x / float(x.sum())).reset_index()

你误读了错误。错误是在索引中找不到“Animal”,而在列中找不到。这里出现的混乱是因为.loc的工作方式。如果只有一个项目传递给.loc,这将被解释为索引。只有第二项用于列。所以你可以用:

gb.loc[:, 'Animal']

但你也可以简单地做到:

gb['Animal']

When I unstack, I'm unable to reset the index so that I can extract the columns

gb.unstack()
gb.loc['Animal']

你可以这样得到“动物”栏: gb.loc[:,'Animal'] 或者 gb['Animal']

相关问题 更多 >