Malintha
Malintha

Reputation: 4766

Dataframe replace all True and False values wirth 1 and 0

I want to replace all True and False values in my dataframe

  A       B      C      D
  12.23   False  43.34  True
  78.56   True   67.78  False

Convert to

      A       B      C      D
      12.23   0      43.34  1
      78.56   1      67.78  0

I tried with following, but it didn't made that change (didn't do any change)

dataset = dataset.replace(True,1)
dataset = dataset.replace(False,0)

Appreciate your insights.

Upvotes: 1

Views: 1613

Answers (1)

rafaelc
rafaelc

Reputation: 59274

Use a dict

>>> df.replace({True:1, False:0})
    A       B   C       D
0   12.23   0   43.34   1
1   78.56   1   67.78   0

From docs, argument to_replace accepts as input

str, regex, list, dict, Series, int, float, or None

For any other (hashable) data types, use their values as keys in a dictionary.

Upvotes: 6

Related Questions