1

A solution would be to use replace() twice:

import pandas as pd
s = pd.Series([True, False, False])

s = s.replace(False, "A")
s = s.replace(True, 'B')

Then,

Out[1]: 
0    B
1    A
2    A

Is there a more elegant way to accomplish this?

ayhan
  • 70,170
  • 20
  • 182
  • 203
user3889486
  • 656
  • 1
  • 7
  • 21

4 Answers4

5

Using numpy.where:

s = np.where(s, 'B', 'A')

This is much faster than map and apply, if you are feeding a Boolean series:

s = pd.Series(np.random.choice([True, False], 1000000))

%%timeit
np.where(s, 'A','B')

4.43 ms ± 94.3 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

mapper={True:'B',False:'A'}

%%timeit
s.map(mapper)

44.1 ms ± 178 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

%%timeit
s.apply(lambda x: 'B' if x else 'A')

126 ms ± 4.51 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

jpp
  • 159,742
  • 34
  • 281
  • 339
3

Using map

mapper={True:'B',False:'A'}
s = s.map(mapper)
s
Out[598]: 
0    B
1    A
2    A
dtype: object
BENY
  • 317,841
  • 20
  • 164
  • 234
1

I'd do it with pandas.Series.apply:

>>> import pandas as pd
>>> s = pd.Series([True, False, False])
>>> s = s.apply(lambda x: 'B' if x else 'A')
>>> s
0    B
1    A
2    A
dtype: object
timgeb
  • 76,762
  • 20
  • 123
  • 145
1

You can use the following command using .map() function:

s = pd.Series([True, False, False])
s = s.map({True: 'A', False: 'B'})
print(s) 

or you can also try the another way using lambda function under .map() function:

s = pd.Series([True, False, False])
s = s.map(lambda x: "A" if x else "B")        
print(s)
Gaurav Sitaula
  • 206
  • 1
  • 7