[英]Change sign of column based on condition
input DF: 输入DF:
value1, value2
123L, 20
222S, 10
222L, 18
I want to make values in volumn value2
where in value1
is L
letter negative, so I am trying to multiply them by -1 我想在值value2
中的值中取值,其中value1
中的L
字母为负,因此我想将它们乘以-1
expexted result: 扩展结果:
value1, value2
123L, -20
222S, 10
222L, -18
my code 我的密码
if np.where(DF['value1'].str.contains('L', case=False)):
DF['value2'] = DF['value2'] * -1
but in output i am receiving all values in column value2
negative. 但是在输出中,我正在接收列value2
所有值都是负数。 How to implement this conditions only for selected rows ? 如何仅对选定的行实施此条件? thanks 谢谢
You can use Boolean indexing with loc
: 您可以对loc
使用布尔索引:
df.loc[df['value1'].str[-1] == 'L', 'value2'] *= -1
Alternatively, using pd.Series.mask
: 或者,使用pd.Series.mask
:
df['value2'].mask(df['value1'].str[-1] == 'L', -df['value2'], inplace=True)
If you are keen on using np.where
, this is possible but verbose: 如果您热衷于使用np.where
,则可以这样np.where
,但很冗长:
df['value2'] = np.where(df['value1'].str[-1] == 'L', -df['value2'], df['value2'])
Notice np.where
is already vectorised, you should not use it in conjunction with if
. 注意np.where
已经被矢量化了,您不应该将它与if
一起使用。
str.endswith
+ loc
str.endswith
+ loc
df.loc[[x.endswith('L') for x in df.value1], 'value2'] *= -1
df
value1 value2
0 123L -20
1 222S 10
2 222L -18
mask
df['value2'] = df.value2.mask(df.value1.str.endswith('L'), -df.value2)
df
value1 value2
0 123L -20
1 222S 10
2 222L -18
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.