2016-08-23 108 views
2

我有一个熊猫数据框我想要有条件地替换某个列。熊猫替换默认值

如:

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()而不使用正则表达式吗?

回答

6

您可以使用map而作为replace,因为快,然后通过3fillna和转换为intastype

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 
+0

可选地(我还没有超时的话) - 'df.col.map(拉姆达L:d.get(L,3))' –

+0

phuuu,它是非常慢的,我得到了[In] [4]:%timeit df ['col3'] = df.col.map(lambda L:d.get(L,3))' '10个循环,最好是3:每循环36.2毫秒' – jezrael

+0

哎哟 - 不是我期望的那么...... df.col.apply(d.get,args =(3,))''怎么样? –