2016-08-23 167 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,))''怎麼樣? –