我有一个简单的熊猫数据帧t
,如下所示:
> print t
group_id item_id traitx
0 groupA 000001-00 True
1 groupA 000002-00 True
2 groupA 000003-00 False
3 groupB 000001-00 True
4 groupC 000002-00 True
5 groupC 000004-00 True
> t.pivot_table(index=['groupid', 'item_id'])
traitx
group_id item_id
groupA 000001-00 True
000002-00 True
000003-00 False
groupB 000001-00 True
groupC 000001-00 True
000002-00 True
目标:我需要计算属于group_id
的行的总数,这些行的traitx
值都是True
。你知道吗
我解决这个问题的想法是以某种方式添加一个列,它将显示整个组对于每一行是否是True
,例如
group_id item_id traitx group_traitx
0 groupA 000001-00 True False
1 groupA 000002-00 True False
2 groupA 000003-00 False False
3 groupB 000001-00 True True
4 groupC 000002-00 True True
5 groupC 000004-00 True True
然后求group_traitx
的和。你知道吗
我可以用以下公式计算group_traitx
:
> print t.groupby('group_id')['traitx'].all()
group_id
groupA False
groupB True
groupC True
Name: traitx, dtype: bool
但是,我不知道如何将结果“涂抹”回原始数据帧中的group_traitx
列。你知道吗
免责声明-我昨天刚开始使用熊猫,所以这可能不是实现我最初目标的最佳方式。你知道吗
您可以使用^{} :
不需要新列:
如果只需要所有
True
组,则使用filter:编辑:
如果在
group_id
和item_id
对中重复:如果需要使用聚合df(唯一对} 聚合:
group_id
和item_id
):pivot_table
使用默认聚合函数mean
,但需要按^{相关问题 更多 >
编程相关推荐