【问题标题】:Pandas to multiple the value of a column that satisfies greater and less than condition熊猫将满足大于和小于条件的列的值倍数
【发布时间】:2019-11-21 16:10:39
【问题描述】:

如何使用pandas对满足大于和小于条件的列的值进行倍增?

df['res'] = ((df['value']<=3) & (df['value']>=1)) * 1.5 *df['value']

df['res'] = ((df['value']<=7) & (df['value']>=4)) * 1.3 *df['value']

以上是我尝试过的。但是,我不断收到消息:

试图在 DataFrame 中的切片副本上设置值。尝试改用 .loc[row_indexer,col_indexer] = value"

当我尝试超过 2 个条件时,“res”变为 0。

以下是我希望达到的目标:

value    res
2        3
6        7.8

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您混淆了两种对象:掩码,即布尔系列,以及数据框的原始列,即具有数值的系列。
    这应该可以解决问题:

    mask1 = (df['value']<=3) & (df['value']>=1)
    mask2 = (df['value']<=7) & (df['value']>=4)
    df.loc[mask1, 'res'] = df['value'] * 1.5
    df.loc[mask2, 'res'] = df['value'] * 1.3
    print(df)
    
       value  res
    0      2  3.0
    2      6  7.8
    

    【讨论】:

      【解决方案2】:

      你可以使用这个来获得一个范围:

      df['res'] = df['value'].between(1, 3, inclusive=True)

      此处包含决定是否应包含端点。

      【讨论】:

        【解决方案3】:

        我建议使用.between方法来创建这样的掩码,即:

        df.loc[df['value'].between(1,3), 'res'] = df[ df['value'].between(1,3), 'value'] * 1.5
        df.loc[df['value'].between(4,7), 'res'] = df[ df['value'].between(4,7), 'value'] * 1.3
        
        

        或者,您也可以使用np.where 函数,它充当 if-else:

        df['res'] = np.where(df['value'].between(1,3), 
                             df['value'] * 1.5,
                             np.where(df['value'].between(4,7),
                                      df['value'] * 1.3,
                                      df['value']))   
        

        【讨论】:

          猜你喜欢
          • 2017-09-10
          • 1970-01-01
          • 2022-07-22
          • 1970-01-01
          • 2018-04-17
          • 1970-01-01
          • 2021-03-01
          • 2016-08-22
          • 2020-06-01
          相关资源
          最近更新 更多