Home > Mobile >  how to make a new 0 and 1 column?
how to make a new 0 and 1 column?

Time:10-28

I have a pandas data frame and I wanna make a new columns with 0 and 1:

if col1 is zero and col2 is positive set new column to 1. if 'col1is zero andcol2is negative set new column to 0. ifcol1is 1 andcol2 is positive set new column to 0. if 'col1 is 1 and col2 is negative set new column to 1.

col1   col2
0       2
0       -4
1       -2
1       5
1       9

new_colum
1
0
1 
0
0

CodePudding user response:

You can determine if col2 is positive and get the absolute difference with col1 (booleans behave like 0/1):

df['new_column'] = df['col1'].sub(df['col2'].gt(0)).abs()

Or, compare the two outputs, you want them to be different:

df['new_column'] = df['col1'].ne(df['col2'].gt(0)).astype(int)

output:

   col1  col2  new_column
0     0     2           1
1     0    -4           0
2     1    -2           1
3     1     5           0
4     1     9           0
  • Related