Home > Enterprise >  Changing a character in a word within a string in pandas
Changing a character in a word within a string in pandas

Time:04-19

I have the following dataframe:

description
#voice-artist,#creative-director
#designer,#asistant

I would like to to replace # with "" and "," with ", "

I do the following but it does not work i.e. I get the same string

df["description"] = df["description"].str.replace("#", "")
df["description"] = df["description"].str.replace(",", ", ")

How can I get what I want?

CodePudding user response:

You may try using regex?

Sample DF:

>>> df
                        description
0  #voice-artist,#creative-director
1               #designer,#asistant

Your Solution, just regex implied ..

>>> df["description"] = df["description"].str.replace("#", "", regex=True)
>>> df["description"] = df["description"].str.replace(",", ", ", regex=True)
>>> df
                       description
0  voice-artist, creative-director
1               designer, asistant

OR:

Try using Series.str.replace instead. It can be useful if you need to replace a substring.

>>> df["description"] = df["description"].str.replace("#", "")
>>> df["description"] = df["description"].str.replace(",", ", ")
>>> df
                       description
0  voice-artist, creative-director
1               designer, asistant
  • Related