2016-09-20 274 views
4

我有以下的數據幀大熊貓:用另一個字符串替換字符串

prod_type 
0 responsive 
1 responsive 
2 respon 
3 r 
4 respon 
5 r 
6 responsive 

我想更換responrresponsive,所以最終的數據幀是

prod_type 
0 responsive 
1 responsive 
2 responsive 
3 responsive 
4 responsive 
5 responsive 
6 responsive 

我試圖以下但它沒有工作:

df['prod_type'] = df['prod_type'].replace({'respon' : 'responsvie'}, regex=True) 
df['prod_type'] = df['prod_type'].replace({'r' : 'responsive'}, regex=True) 

回答

3

解決方案與replacedictionary

df['prod_type'] = df['prod_type'].replace({'respon':'responsive', 'r':'responsive'}) 
print (df) 
    prod_type 
0 responsive 
1 responsive 
2 responsive 
3 responsive 
4 responsive 
5 responsive 
6 responsive 

如果需要設置在列中的所有值給部分string

df['prod_type'] = 'responsive' 
+0

謝謝!有效。 –

+1

@Carlton Gibson - 謝謝。 – jezrael

2

Yo ü不需要路過這裏regex=True,因爲這將查找部分匹配,如精確的特殊照顧後僅匹配傳遞PARAMS作爲單獨的ARGS:

In [7]: 
df['prod_type'] = df['prod_type'].replace('respon' ,'responsvie') 
df['prod_type'] = df['prod_type'].replace('r', 'responsive') 
df 

Out[7]: 
    prod_type 
0 responsive 
1 responsive 
2 responsvie 
3 responsive 
4 responsvie 
5 responsive 
6 responsive 
2

其他解決方案的情況下,從所有項目將是相同的:

df['prod_type'] = ['responsive' for item in df['prod_type']] 
In[0]: df 
Out[0]: 
prod_type 
0 responsive 
1 responsive 
2 responsive 
3 responsive 
4 responsive 
5 responsive 
6 responsive