1

I have a dataframe from which I need to replace all strings in column sense where the string is exactly pertain. I can apply the following code to do the same

pd[pd['sense'] == 'pertain']['sense'].str.replace('pertain','pertaining')

But this does not take effect on the original dataframe. How can I make sure that the effect takes palce on the original dataset and all the pertain in the column will change to 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]].

So Ideally, after the operation my output should look like the following

 | 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]].

1 Answer 1

2

You can use loc with assignment, where you pass a logical vector to indicate rows where the column sense's value should be replaced (assuming your data frame is named 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]].

Another method is to use replace only on sense column and then assign it back to the original data frame, which replaces the sense column with modified version:

df['sense'] = df.sense.replace("pertain", "pertaining")

With all being said, your method also works, you just need to assign it back to your original data frame as the second option above.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.