我试图在一列中替换多个字符串值,我知道我可以使用replace()
逐个执行。考虑到我需要替换超过10个字符串值,我只是想知道是否有一种更快的方法来替换多个字符串值为相同的值。
df = pd.DataFrame({'a':["US", "Japan", "UK", "China", "Peru", "Germany"]})
df.replace({'a' : { 'Japan' : 'Germany', 'UK' : 'Germany', 'China' : 'Germany' }})
预期输出:
a
0 US
1 Germany
2 Germany
3 Germany
4 Peru
5 Germany
使用numpy.where
和Series.isin
:
#60k rows
df = pd.DataFrame({'a':["US", "Japan", "UK", "China", "Peru", "Germany"] * 10000})
In [161]: %timeit df['a'] = df.a.map({ 'Japan' : 'Germany', 'UK' : 'Germany', 'China' : 'Germany' }).fillna(df.a)
12.4 ms ± 501 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
In [162]: %timeit df['a'] = np.where(df.a.isin(['Japan','UK','China']), 'Germany', df.a)
4.27 ms ± 379 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
#assignment raise error in test
In [1632]: %timeit df.replace({'a' : { 'Japan' : 'Germany', 'UK' : 'Germany', 'China' : 'Germany' }})
7.85 ms ± 462 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
Slowier解决方案:
In [157]: %timeit df.replace('Japan|UK|China', 'Germany', regex=True)
218 ms ± 842 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)
使用说明:
df = df.replace('Japan|UK|China', 'Germany', regex=True)