Search code examples
pythonpandasdataframenumpyseries

How to Invert column values in pandas - pythonic way?


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

Solution

  • 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