Home > Software design >  How to Invert column values in pandas - pythonic way?
How to Invert column values in pandas - pythonic way?

Time:02-08

I have a dataframe like as shown below

cdf = pd.DataFrame({'Id':[1,2,3,4,5],
                    'Label':[1,1,1,0,0]})

My objective is to

a) replace 0s as 1s AND 1s as 0s in Label column

I was trying something like the below

cdf.assign(invert_label=cdf.Label.loc[::-1].reset_index(drop=True)) #not work
cdf['invert_label'] = np.where(cdf['Label']==0, '1', '0')

' but this doesn't work. It reverses the order

I expect my output to be like as shown below

    Id  Label
0   1   0
1   2   0
2   3   0
3   4   1
4   5   1

CodePudding user response:

You can compare 0, so for 0 get Trues and for not 0 get Falses, then converting to integers for mapping True, False to 1, 0:

print (cdf['Label'].eq(0))
0    False
1    False
2    False
3     True
4     True
Name: Label, dtype: bool

cdf['invert_label'] = cdf['Label'].eq(0).astype(int)

print (cdf)
   Id  Label  invert_label
0   1      1             0
1   2      1             0
2   3      1             0
3   4      0             1
4   5      0             1

Another idea is use mapping:

cdf['invert_label'] = cdf['Label'].map({1:0, 0:1})

print (cdf)
   Id  Label  invert_label
0   1      1             0
1   2      1             0
2   3      1             0
3   4      0             1
4   5      0             1

CodePudding user response:

One maybe obvious answer might be to use 1-value:

cdf['Label2'] = 1-cdf['Label']

output:

   Id  Label  Label2
0   1      1       0
1   2      1       0
2   3      1       0
3   4      0       1
4   5      0       1

CodePudding user response:

You could map the not function as well -

import operator
cdf['Label'].map(operator.not_).astype('int')

CodePudding user response:

Another way, and I am adding this as a separate answer as this is probably not "pythonic" enough (in the sense that it is not very explicit) is to use the bitwise xor

cdf['Label'] ^ 1
  •  Tags:  
  • Related