user3889486
user3889486

Reputation: 656

How to replace a Series of booleans with a Series of strings?

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?

Upvotes: 1

Views: 76

Answers (4)

jpp
jpp

Reputation: 164673

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)

Upvotes: 5

Gaurav Sitaula
Gaurav Sitaula

Reputation: 216

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)

Upvotes: 1

BENY
BENY

Reputation: 323226

Using map

mapper={True:'B',False:'A'}
s = s.map(mapper)
s
Out[598]: 
0    B
1    A
2    A
dtype: object

Upvotes: 3

timgeb
timgeb

Reputation: 78690

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

Upvotes: 1

Related Questions