gpt4 book ai didi

Python/Pandas 条件多列划分(示例代码)

转载 作者:行者123 更新时间:2023-11-28 22:15:07 24 4
gpt4 key购买 nike

有一个像这样的 DataFrame:

type  A  B  total
1 4 5 9
2 5 5 10
1 4 1 5

是否可以应用此代码:

df[['A','B']] = df[['A','B']].div(df['total'], axis=0)

但是基于条件,我的意思是仅当类型 == 1 时才应用它,同时保持其他值(类型 == 2)不变并且不修改(子集化)数据框作为除法的结果?

最佳答案

您可以使用 bool 掩码;事实上,pd.DataFrame.mask在这里工作:

cond = df['type'].eq(1)

df[['A', 'B']] = df[['A', 'B']].mask(cond, df[['A','B']].div(df['total'], 0))

print(df)

type A B total
0 1 0.444444 0.555556 9
1 2 5.000000 5.000000 10
2 1 0.800000 0.200000 5

关于Python/Pandas 条件多列划分(示例代码),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53011693/

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