[英]How to assign values on multiple columns of a pandas data frame based on condition
I have a dtaframe df as below我有一个 dtaframe df 如下
df = pd.DataFrame({
'A': [20,30,40,-50,60,-70 ],
'B': [21, -19, 20, 18, 17, -21],
'C': [1,12,-13,14,15,16],
'D': [-88, 92, 9, 70, -6, 78]})
I want every value on column ['C','D'] to be zero where the value is between -10 and 10, rest of the values should remain same.我希望 ['C','D'] 列上的每个值都为零,其中值介于 -10 和 10 之间,其余值应保持不变。
is there something similar to data.series.between
, which can be applied to a data frame df[(df[['C','D']].between(-10,10,inclusive=True)]=0
是否有类似于
data.series.between
东西,可以应用于数据框df[(df[['C','D']].between(-10,10,inclusive=True)]=0
output should be :输出应该是:
A B C D
0 20 21 0 -88
1 30 -19 12 92
2 40 20 -13 0
3 -50 18 14 70
4 60 17 15 0
5 -70 -21 16 78
You can use df.mask()
here after comparing by df.ge
and df.le
:通过
df.ge
和df.le
进行比较后,您可以在此处使用df.mask()
:
df[['C','D']]=df[['C','D']].mask(df[['C','D']].ge(-10)&df[['C','D']].le(10),0)
Or np.where()
:或
np.where()
:
df[['C','D']]=np.where(df[['C','D']].ge(-10)&df[['C','D']].le(10),0,df[['C','D']])
A B C D
0 20 21 0 -88
1 30 -19 12 92
2 40 20 -13 0
3 -50 18 14 70
4 60 17 15 0
5 -70 -21 16 78
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.