我有一个数据框,需要从其中替换字符串sense
中的所有字符串,其中字符串恰好是pertain
。我可以应用以下代码进行相同的操作pd[pd['sense'] == 'pertain']['sense'].str.replace('pertain','pertaining')
但这对原始数据帧无效。我如何确保效果对原始数据集有效,并且列中的所有pertain
都将更改为pertaining
| affix | word | sense | meaning |
0 ical neuroanatomical pertaining of or pertaining to [[neuroanatomy]]
1 ical neuroanatomical pertain of or pertaining to [[neuroanatomy]]
2 ical biotechnological pertaining of or pertaining to [[biotechnology]]
3 ical biotechnological pertain of or pertaining to [[biotechnology]]
4 ical educological relating relating to [[educology]].
因此理想情况下,在操作之后,我的输出应如下所示
| affix | word | sense | meaning |
0 ical neuroanatomical pertaining of or pertaining to [[neuroanatomy]]
1 ical neuroanatomical pertaining of or pertaining to [[neuroanatomy]]
2 ical biotechnological pertaining of or pertaining to [[biotechnology]]
3 ical biotechnological pertaining of or pertaining to [[biotechnology]]
4 ical educological relating relating to [[educology]].
最佳答案
可以将loc
与赋值配合使用,在其中传递逻辑向量以指示应替换列sense
的值的行(假设数据框名为df
):
df.loc[df.sense == "pertain", "sense"] = "pertaining"
df
# affix word sense meaning
#0 ical neuroanatomical pertaining of or pertaining to [[neuroanatomy]]
#1 ical neuroanatomical pertaining of or pertaining to [[neuroanatomy]]
#2 ical biotechnological pertaining of or pertaining to [[biotechnology]]
#3 ical biotechnological pertaining of or pertaining to [[biotechnology]]
#4 ical educological relating relating to [[educology]].
另一种方法是仅在
replace
列上使用sense
,然后将其分配回原始数据框,该数据框将修改后的版本替换为sense
列:df['sense'] = df.sense.replace("pertain", "pertaining")
综上所述,您的方法也可以使用,您只需要将其分配回原始数据框即可,这是上面的第二个选项。
关于python - 如何在符合条件的选定行上替换列中的字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41657610/