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

后端 未结 8 2290
醉酒成梦
醉酒成梦 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:54

    Note the tilda that reverses the selection. It uses pandas methods (i.e. is faster than if/else).

    df.loc[(df['c1'] == 'Value'), 'c2'] = 10
    df.loc[~(df['c1'] == 'Value'), 'c2'] = df['c3']
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题