gpt4 book ai didi

python - 根据条件更改列的符号

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

输入方向:

value1, value2
123L, 20
222S, 10
222L, 18

我想在 volumn value2 中设置值,其中 value1L 字母负数,所以我试图将它们乘以 -1

扩展结果:

value1, value2
123L, -20
222S, 10
222L, -18

我的代码

if np.where(DF['value1'].str.contains('L', case=False)):
DF['value2'] = DF['value2'] * -1

但在输出中,我收到列 value2 中的所有值都是负值。如何仅对选定的行实现此条件?谢谢

最佳答案

您可以将 bool 索引与 loc 一起使用:

df.loc[df['value1'].str[-1] == 'L', 'value2'] *= -1

或者,使用 pd.Series.mask :

df['value2'].mask(df['value1'].str[-1] == 'L', -df['value2'], inplace=True)

如果您热衷于使用 np.where ,这是可能的,但很冗长:

df['value2'] = np.where(df['value1'].str[-1] == 'L', -df['value2'], df['value2'])

注意 np.where 已经被矢量化了,你不应该将它与 if 一起使用。

关于python - 根据条件更改列的符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54132072/

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