我有以下数据框
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)
答案 0 :(得分:6)
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'
:
{{1}}
答案 1 :(得分:2)
你不需要在这里传递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 :(得分:2)
如果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
答案 3 :(得分:1)
或者,您可以将应用功能与lambda语法一起使用
df['prod_type'] = df['prod_type'].apply(lambda x: x.replace('respon', 'responsvie'))