2

Whilst applying the below function I have bool values converted to integers.

What am I missing?

import pandas as pd

def multi(x):
    if isinstance(x, (float, int)):
        return x * 10
    return x

print(pd.DataFrame(data={"a": [True, False]}).applymap(func=multi))

Ouput:

    a
0  10
1   0

Expected:

       a
0   True
1   False
Dave
  • 424
  • 3
  • 14

2 Answers2

1

It's because:

>>> isinstance(True, int)
True
>>> 

True is actually 1!

And False is actually 0, so you're kinda attempting this approach strangely.

To fix it, use type:

def multi(x):
    if type(x) in (float, int)):
        return x * 10
    return x
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
1

Booleans are treated as integers (1, 0) when you're multiplying with a numeric. So when you do

True * 10 #(= 1 * 10)

the output is

10

Similarly,

False * 10 #(= 0 * 10)

will equal 0

This is because Boolean is a subclass of int. You can read about it here

Mohit Motwani
  • 4,662
  • 3
  • 17
  • 45