Python 熊猫:用另一个字符串替换字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39602824/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 22:30:25  来源:igfitidea点击:

pandas: replace string with another string

pythonstringpython-2.7pandasreplace

提问by chintan s

I have the following data frame

我有以下数据框

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

I would like to replace responand rwith responsive, so the final data frame is

我想更换responr使用responsive,所以最终的数据帧

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

I tried the following but it did not work:

我尝试了以下但没有奏效:

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

回答by jezrael

Solution with replaceby dictionary:

解决方案与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

If need set all values in column to some string:

如果需要将列中的所有值设置为 some string

df['prod_type'] = 'responsive' 

回答by EdChum

You don't need to pass regex=Truehere, as this will look for partial matches, as you''re after exact matches just pass the params as separate args:

你不需要在regex=True这里传递,因为这将寻找部分匹配,因为你在精确匹配之后只需将参数作为单独的参数传递:

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

回答by estebanpdl

Other solution in case all items from df['prod_type']will be the same:

其他解决方案,以防来自的所有项目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