1

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
2
  • 1
    cdf['invert_label'] = np.where(cdf['Label']==0, '1', '0') not working for you? for me working Commented Feb 8, 2022 at 9:52
  • 4
    df.Label ^= 1 Commented Feb 8, 2022 at 10:14

4 Answers 4

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

You could map the not function as well -

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

Comments

-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.