Geoff Nel
Geoff Nel

Reputation: 3

Flip 0 and 1 bits in pandas DataFrame efficiently?

I had an issue switching a binary variable in-place for a large DF... this ended up working; posting in case this is an issue for another user.

dfSet2['TargetDefault'] = dfSet2.apply(
    lambda x: (0 if x['TargetDefault']==1 else 1), axis=1)

Is there a faster/easier way to do this?

enter image description here

Upvotes: 0

Views: 1055

Answers (2)

cs95
cs95

Reputation: 402603

It's as simple as

dfSet2['TargetDefault'] = 1 - dfSet2['TargetDefault']

Upvotes: 0

anishtain4
anishtain4

Reputation: 2402

So if I got it right, you have them as 0 and 1 and want to swap them?

df['coli'] = (~df.coli.astype(bool)).astype(int)

Upvotes: 2

Related Questions