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

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

    You can use pandas.DataFrame.mask to add virtually as many conditions as you need:

    data = {'a': [1,2,3,4,5], 'b': [6,8,9,10,11]}
    
    d = pd.DataFrame.from_dict(data, orient='columns')
    c = {'c1': (2, 'Value1'), 'c2': (3, 'Value2'), 'c3': (5, d['b'])}
    
    d['new'] = np.nan
    for value in c.values():
        d['new'].mask(d['a'] == value[0], value[1], inplace=True)
    
    d['new'] = d['new'].fillna('Else')
    d
    

    Output:

        a   b   new
    0   1   6   Else
    1   2   8   Value1
    2   3   9   Value2
    3   4   10  Else
    4   5   11  11
    

提交回复
热议问题