你好,我有一个数据框,如下所示,我需要替换每个组中的列值,基于使用Pandas 的条件.请帮帮忙

输入数据:

Name    Thing   type    flag
Steve   Car     High    NULL
Steve   Car     Low     NULL
Steve   Bike    Low     NULL
Steve   Bike    Avg     X
Steve   Plane   High    NULL
Steve   Plane   Low     NULL

条件是:

1. for a given name and thing if type is Low,Avg update the flag as X

2. for a given name and thing if type is High,Avg update the flag as X

预期输出:

Name    Thing   type    flag
Steve   Car     High    NULL
Steve   Car     Low     NULL
Steve   Bike    Low     X
Steve   Bike    Avg     X
Steve   Plane   High    NULL
Steve   Plane   Low     NULL

到目前为止已try :

df['flag'] = df['flag'].mask((df['type'] == 'Low') | (df['type'] == 'Avg'), 'X').groupby(df(['name','thing'])).transform('any')

推荐答案

Code

g = df.groupby(['Name', 'Thing'])['type']
cond = g.transform(lambda x: (set(x) == {'Low', 'Avg'}) | (set(x) == {'High', 'Avg'}))
df.loc[cond, 'flag'] = 'X'

Df:

    Name  Thing  type flag
0  Steve    Car  High  NaN
1  Steve    Car   Low  NaN
2  Steve   Bike   Low    X
3  Steve   Bike   Avg    X
4  Steve  Plane  High  NaN
5  Steve  Plane   Low  NaN

Python-3.x相关问答推荐

网站抓取:当我使用Chrome DevTools中的网络选项卡时,找不到正确的URL来提供我想要的数据

tkinter treeview 如何在获取所选项目时将设置的对象作为对象返回

python3,将整数转换为字节:对于小整数使用 to_bytes() 有哪些替代方法?

需要找到完全匹配并使用正则表达式替换

如何通过 python 使用 auth no priv 获取 SNMPv3?

如何在类中的函数(以 self 作为第一个参数)中使用递归

在不改变 python 中原始数组顺序的情况下,对多维字符串数组进行降序排序?

无法提出给定 for 循环的原因 (Python 3.11)

如何将搜索结果中的所有值保存在另一个列表中?

python2和python3中的列表生成器

在python中将字符串写入文本文件

正则表达式:匹配字符串中的分隔符(字母和特殊字符)以形成新的子字符串

正则表达式从文本文件中捕获包含制表符/空格和子字符串的部分字符串

参数化泛型不能与类或实例判断一起使用

简单的 get/post 请求在 python 3 中被阻止,但在 python 2 中没有

PySpark python 问题:Py4JJavaError: An error occurred while calling o48.showString

如何在多核上运行 Keras?

接收导入错误:没有名为 *** 的模块,但有 __init__.py

类方法和实例方法同名

混合全局/参数和名为top的函数的奇怪python行为