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

后端 未结 8 2459
醉酒成梦
醉酒成梦 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']
    

提交回复
热议问题