gpt4 book ai didi

python - 如何替换匹配条件的选定行的列中的字符串

转载 作者:行者123 更新时间:2023-12-01 03:23:34 26 4
gpt4 key购买 nike

我有一个数据帧,需要从中替换 sense 列中的所有字符串,其中该字符串恰好所属。我可以应用以下代码来执行相同的操作

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]].
<小时/>

另一种方法是仅在 sense 列上使用 replace,然后将其分配回原始数据框,从而替换 sense 列修改后的版本:

df['sense'] = df.sense.replace("pertain", "pertaining")
<小时/>

综上所述,您的方法也有效,您只需将其分配回原始数据框,如上面的第二个选项。

关于python - 如何替换匹配条件的选定行的列中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41657610/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com