gpt4 book ai didi

python - bool 列上的条件 DataFrame 过滤器?

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

如果我有这样的 DataFrame:

| id     | attribute_1 | attribute_2 |
|--------|-------------|-------------|
| 123abc | TRUE | TRUE |
| 123abc | TRUE | FALSE |
| 456def | TRUE | FALSE |
| 789ghi | TRUE | TRUE |
| 789ghi | FALSE | FALSE |
| 789ghi | FALSE | FALSE |

如何应用groupby或一些等效的过滤器来计算DataFrame子集中id元素的唯一数量,如下所示:

| id     | attribute_1 | attribute_2 |
|--------|-------------|-------------|
| 123abc | TRUE | TRUE |
| 123abc | TRUE | FALSE |

意思是,我想获取给定 id 的所有实例的 id 值的唯一数量,其中 attribute_1 == True >但是attribute_2必须至少有1个True

因此,456def 不会包含在过滤器中,因为它的 attribute_2 至少没有一个 True

789ghi 不会包含在过滤器中,因为它的所有 attribute_1 条目都不是 True

最佳答案

您需要groupby两次,一次使用transform('all')对“attribute_1”进行分组,第二次使用transform('any' ) 在“attribute_2”上。

i = df[df.groupby('id').attribute_1.transform('all')]
j = i[i.groupby('id').attribute_2.transform('any')]

print (j)
id attribute_1 attribute_2
0 123abc True True
1 123abc True False

最后,要获取满足此条件的唯一 ID,请调用 nunique:

print (j['id'].nunique())
1

当您的 attribute_* 列是 bool 值时,这是最容易做到的。如果它们是字符串,请先修复它们:

df = df.replace({'TRUE': True, 'FALSE': False})

关于python - bool 列上的条件 DataFrame 过滤器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52284417/

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