pandas 中的条件方法链接

NJL*_*NJL 3 python if-statement method-chaining pandas

在使用 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"
)
Run Code Online (Sandbox Code Playgroud)

谢谢你!

moz*_*way 6

您可以使用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)
)
Run Code Online (Sandbox Code Playgroud)

输出change_to_numeric = False

     A    B
0  one  one
Run Code Online (Sandbox Code Playgroud)

输出change_to_numeric = True

   A  B
0  1  1
Run Code Online (Sandbox Code Playgroud)