根据条件向pandas df添加新列 [英] Adding new column to pandas df based on condition

查看:105
本文介绍了根据条件向pandas df添加新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据集:

ID   Asset   Boolean
1     "A"    True  
1     "B"    False  
1     "B"    False   
2     "A"    True
3     "A"    True
3     "A"    True
3     "B"    False
3     "B"    False
4     "A"    True
4     "A"    True
5     "A"    True
5     "B"    False

我想添加另一列,只有当 Boolean 列中的所有值对于相同的 ID 的计算结果都为 True 时,该列才应计算为 True.所以是这样的:

I want to add another column, which should evaluate to True only if all values in the column Boolean evaluate to True for the same ID. So something like this:

ID   Asset   Boolean  Check
1     "A"    True     False
1     "B"    False    False
1     "B"    False    False
2     "A"    True     True
3     "A"    True     False
3     "A"    True     False
3     "B"    False    False
3     "B"    False    False
4     "A"    True     True
4     "A"    True     True
5     "A"    True     False
5     "B"    False    False

我想保留过滤器选项的原始数据集.我不知道如何在考虑 ID 列的情况下遍历 Boolean 列.

I want to keep the original dataset for filter options. I could not figure out, how to iterate through the Boolean column taking the ID column into consideration.

推荐答案

您可以GroupBytransformall:

df['Check'] = df.groupby('ID').Boolean.transform('all')

print(df)

    ID Asset  Boolean  Check
0    1     A     True  False
1    1     B    False  False
2    1     B    False  False
3    2     A     True   True
4    3     A     True  False
5    3     A     True  False
6    3     B    False  False
7    3     B    False  False
8    4     A     True   True
9    4     A     True   True
10   5     A     True  False
11   5     B    False  False

这篇关于根据条件向pandas df添加新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆