pandas:用另一个字符串替换字符串
Posted
技术标签:
【中文标题】pandas:用另一个字符串替换字符串【英文标题】:pandas: replace string with another string 【发布时间】:2017-01-28 21:26:50 【问题描述】:我有以下数据框
prod_type
0 responsive
1 responsive
2 respon
3 r
4 respon
5 r
6 responsive
我想把respon
和r
换成responsive
,所以最终的数据框是
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)
【问题讨论】:
【参考方案1】:按照jezrael的回答,可以设置inplace=True
改变数据框:
df = pd.DataFrame(
'prod_type':['responsive','responsive','respon','r','respon','r','responsive'],
columns=['prod_type'])
df.replace('prod_type': 'respon': 'responsive', 'r': 'responsive', inplace=True)
df
prod_type
0 responsive
1 responsive
2 responsive
3 responsive
4 responsive
5 responsive
6 responsive
【讨论】:
【参考方案2】:或者,您可以使用带有 lambda 语法的 apply 函数
df['prod_type'] = df['prod_type'].apply(lambda x: x.replace('respon', 'responsvie'))
【讨论】:
【参考方案3】:replace
dictionary
的解决方案:
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'
【讨论】:
【参考方案4】:如果df['prod_type']
中的所有项目都相同的其他解决方案:
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
【讨论】:
【参考方案5】:您无需在此处传递 regex=True
,因为这将查找部分匹配项,因为您在完全匹配之后只需将参数作为单独的 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
【讨论】:
以上是关于pandas:用另一个字符串替换字符串的主要内容,如果未能解决你的问题,请参考以下文章
用另一个替换特定字符串 - String#replaceAll()