简体   繁体   English

如何根据条件在熊猫数据框的多列上分配值

[英]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.gedf.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.

相关问题 如何基于熊猫中的多个列分配值? - How to assign values based on multiple columns in pandas? 根据条件修改 pandas 数据框值 - Modify pandas data frame values based on condition 如何在熊猫数据框中为切片分配值 - How to assign values to a slice in a pandas data frame 如何根据合并的数据框之一的两列的值在熊猫数据框中添加值 - How to add values in a pandas data frame based on values of two columns of one of the data frame merged 如何根据pandas中另一个数据框中的条件更新数据框 - how to update a data frame based on the condition in another data frame in pandas Python pandas:根据条件从多个数据框中访问数据 - Python pandas: Accessing data from multiple data frame based on condition python 如何将一个 pandas 数据帧中的值计数转置到第二个数据帧中的多列? - python How to transpose the count of values in one pandas data frame to multiple columns in a second data frame? 在带有日期的多列上使用多个条件对熊猫数据框进行子集 - Subset pandas data frame with multiple condition on several columns with date 在根据条件比较 2 个数据框列后,如何创建新的 pandas dataframe? - How do I create a new pandas dataframe after comparing 2 data frame columns based on a condition? 根据if条件为熊猫数据框中的列分配值 - assigning values to column in pandas data-frame based on if condition
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM