熊猫增加条件值到另一列

时间:2020-08-20 12:59:14

标签: python pandas

这种方法有什么问题

df['max'] = np.where((df[df['category'] == 'basket']['width'] == 0), df['max']+10, df['max'])

因此,基本上我想根据df['max']等于篮子且宽度等于df['category']的情况来更新0。如果是这种情况,我想将所有df['max']的值增加10,否则我想保持不变。

这将返回以下错误

ValueError: operands could not be broadcast together with shapes (17,) (55,) (55,) 

输入

    max    category   width
0   181     basket     0  
1   745     basket     10

所需的输出

    max    category   width
0   191     basket     0  
1   745     basket     10

1 个答案:

答案 0 :(得分:1)

在给定输入的情况下,这对我很有效。

df["max"] = np.where((df["category"]=="basket")&(df["width"]==0), df["max"]+10, df["max"])
print(df)

   max category  width
0  191   basket      0
1  745   basket     10