Pandas/Python: Set value of one column based on value in another column

后端 未结 8 2463
醉酒成梦
醉酒成梦 2020-11-28 22:57

I need to set the value of one column based on the value of another in a Pandas dataframe. This is the logic:

if df[\'c1\'] == \'Value\':
    df[\'c2\'] = 10         


        
8条回答
  •  难免孤独
    2020-11-28 23:55

    You can use np.where() to set values based on a specified condition:

    #df
       c1  c2  c3
    0   4   2   1
    1   8   7   9
    2   1   5   8
    3   3   3   5
    4   3   6   8
    

    Now change values (or set) in column ['c2'] based on your condition.

    df['c2'] = np.where(df.c1 == 8,'X', df.c3)
    
       c1  c3  c4
    0   4   1   1
    1   8   9   X
    2   1   8   8
    3   3   5   5
    4   3   8   8
    

提交回复
热议问题