我有一个pandas数据帧我想有条件地替换某个列。
例如:
col
0 Mr
1 Miss
2 Mr
3 Mrs
4 Col.
我想将它们映射为
{'Mr': 0, 'Mrs': 1, 'Miss': 2}
如果dict中现在有其他标题可用,那么我希望它们的默认值为3
上面的例子变成了
col
0 0
1 2
2 0
3 1
4 3
我可以使用pandas.replace()而不使用正则表达式吗?
你可以使用map
而不是replace
,因为更快,然后由fillna
3
并由int
施放到astype
:
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
添加@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的第一个参数是一个返回默认值的函数。