gpt4 book ai didi

python - pandas groupby 多列

转载 作者:行者123 更新时间:2023-12-01 02:24:01 25 4
gpt4 key购买 nike

我有一个数据集,其中包含状态代码及其状态。

  code  status
1 AZ a
2 CA b
3 KS c
4 MO c
5 NY d
6 AZ d
7 MO a
8 MO b
9 MN b
10 NV a
11 NV e
12 MO f
13 NY a
14 NY a
15 NY b

我想过滤掉这个代码只包含 a 的数据集状态并计算他们有多少。示例输出将是,

  code  status  
1 AZ a
2 MO a
3 NY a

AZ =1 MO = 1 NY =2

我用过df.groupyby("code").loc[df.status == 'a']但没有任何运气。任何帮助表示赞赏!

最佳答案

让我们首先过滤数据帧中的 a,然后进行 groupby 和 count。

df[df.status == 'a'].groupby('code').size()

输出:

code
AZ 1
MO 1
NV 1
NY 2
dtype: int64

关于python - pandas groupby 多列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47584414/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com