how to compute a new column based on the values of other columns in pandas - python

前端 未结 4 1131
野性不改
野性不改 2021-01-13 01:26

Let\'s say my data frame contains these data:

>>> df = pd.DataFrame({\'a\':[\'l1\',\'l2\',\'l1\',\'l2\',\'l1\',\'l2\'],
                       \'b\'         


        
4条回答
  •  臣服心动
    2021-01-13 01:55

    You can just use logical operators. I'm not sure why you're using strings of 1 and 2 rather than ints, but here's a solution. The astype at the end converts it from boolean to 0's and 1's.

    df['c'] = (((df['a'] == 'l1')&(df['b']=='1'))|((df['a'] == 'l2')&(df['b']=='2'))).astype(int)

提交回复
热议问题