Dogukan Yılmaz
Dogukan Yılmaz

Reputation: 556

Changing a character in a word within a string in pandas

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?

Upvotes: 0

Views: 49

Answers (1)

Karn Kumar
Karn Kumar

Reputation: 8816

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

Upvotes: 1

Related Questions