gpt4 book ai didi

python - pandas 中的条件方法链接

转载 作者:行者123 更新时间:2023-12-03 08:03:53 26 4
gpt4 key购买 nike

在 pandas 中使用方法链时,是否有一种简单的通用方法可以使方法以 if 语句为条件?

模拟示例:

df = pd.DataFrame({'A':['one', 'two'], 'B':['one', 'two']})

change_to_numeric = False

df = (df
.query("A == 'one'")
.replace('one', 1) # <-- Execute this row only "if change_to_numeric == True"
)

谢谢!

最佳答案

您可以使用pipe :

df = pd.DataFrame({'A':['one', 'two'], 'B':['one', 'two']})

change_to_numeric = False

df = (df
.query("A == 'one'")
.pipe(lambda d: d.replace('one', 1) if change_to_numeric else d)
)

change_to_numeric = False 的输出:

     A    B
0 one one

change_to_numeric = True 的输出:

   A  B
0 1 1

关于python - pandas 中的条件方法链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73078014/

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