我有一个pandas数据框,我想有条件地替换某个列。
例如:
col
0 Mr
1 Miss
2 Mr
3 Mrs
4 Col.
我想将它们映射为
{'Mr': 0, 'Mrs': 1, 'Miss': 2}
如果字典中现在有其他标题可用,那么我希望它们的默认值为3
上面的例子变成
col
0 0
1 2
2 0
3 1
4 3
我可以在不使用正则表达式的情况下使用pandas.replace()来做这件事吗?
发布于 2016-08-23 15:06:20
您可以使用map
而不是replace
,因为更快,然后3
使用fillna
,astype
转换为int
df['col'] = df.col.map({'Mr': 0, 'Mrs': 1, 'Miss': 2}).fillna(3).astype(int)
print (df)
col
0 0
1 2
2 0
3 1
4 3
使用numpy.where
的另一种解决方案和使用isin
的条件
d = {'Mr': 0, 'Mrs': 1, 'Miss': 2}
df['col'] = np.where(df.col.isin(d.keys()), df.col.map(d), 3).astype(int)
print (df)
col
0 0
1 2
2 0
3 1
4 3
使用replace
的解决方案
d = {'Mr': 0, 'Mrs': 1, 'Miss': 2}
df['col'] = np.where(df.col.isin(d.keys()), df.col.replace(d), 3)
print (df)
col
0 0
1 2
2 0
3 1
4 3
计时
df = pd.concat([df]*10000).reset_index(drop=True)
d = {'Mr': 0, 'Mrs': 1, 'Miss': 2}
df['col0'] = df.col.map(d).fillna(3).astype(int)
df['col1'] = np.where(df.col.isin(d.keys()), df.col.replace(d), 3)
df['col2'] = np.where(df.col.isin(d.keys()), df.col.map(d), 3).astype(int)
print (df)
In [447]: %timeit df['col0'] = df.col.map(d).fillna(3).astype(int)
100 loops, best of 3: 4.93 ms per loop
In [448]: %timeit df['col1'] = np.where(df.col.isin(d.keys()), df.col.replace(d), 3)
100 loops, best of 3: 14.3 ms per loop
In [449]: %timeit df['col2'] = np.where(df.col.isin(d.keys()), df.col.map(d), 3).astype(int)
100 loops, best of 3: 7.68 ms per loop
In [450]: %timeit df['col3'] = df.col.map(lambda L: d.get(L, 3))
10 loops, best of 3: 36.2 ms per loop
发布于 2019-04-04 08:47:29
根据@jezrael的回答:最直接的解决方案是使用defaultdict而不是dict。当您不希望缺失值被您的默认值替换时,这一点尤其有用。
from collections import defaultdict
df['col'] = df.col.map(defaultdict(lambda: 3,Mr= 0, Mrs= 1, Miss= 2),na_action='ignore')
defaultdict的第一个参数是一个返回默认值的函数。
https://stackoverflow.com/questions/39104730
复制相似问题