如何用一系列字符串替换一系列布尔值?

use*_*486 1 python pandas

解决方案是使用replace()两次:

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

s = s.replace(False, "A")
s = s.replace(True, 'B')
Run Code Online (Sandbox Code Playgroud)

然后,

Out[1]: 
0    B
1    A
2    A
Run Code Online (Sandbox Code Playgroud)

是否有更优雅的方式来实现这一目标?

jpp*_*jpp 5

使用numpy.where:

s = np.where(s, 'B', 'A')
Run Code Online (Sandbox Code Playgroud)

这比map并且apply,如果你喂一个布尔系列要快得多:

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

%%timeit
np.where(s, 'A','B')
Run Code Online (Sandbox Code Playgroud)

每循环4.43 ms±94.3μs(平均值±标准偏差,7次运行,每次100次循环)

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

%%timeit
s.map(mapper)
Run Code Online (Sandbox Code Playgroud)

每循环44.1 ms±178μs(7次运行的平均值±标准偏差,每次10次循环)

%%timeit
s.apply(lambda x: 'B' if x else 'A')
Run Code Online (Sandbox Code Playgroud)

每循环126 ms±4.51 ms(平均值±标准偏差,7次运行,每次10次循环)