如何在条件上对数据帧进行分组?

2024-04-25 14:48:16 发布

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

我想在一个函数上使用条件groupby

test = pd.DataFrame({'A':range(9), 'B':['this','this','this','that','and','the','other','thing','.']})

根据“B”==“this”(我如何想象这个w/A查询结构)对“A”进行分组:

test['A'].groupby("B == 'this'").sum()

应返回此:[3,33]

pd.Series([3,33])

谢谢你


Tags: andthe函数testdataframethatrangethis
1条回答
网友
1楼 · 发布于 2024-04-25 14:48:16

groupby如果您传递另一个相同长度的序列,则它将起作用,因此您可以先计算条件序列,然后按其分组:

test.groupby(test.B == "this").sum()
#        A
#    B  
#False  33
# True   3

相关问题 更多 >