6

What is the equivalent of R's sub / gsub functions for Python pandas' Series or DataFrame ?

For example, in R, my code is

schData<-gsub("/"," by ",schData,ignore.case=F)

What would be equivalent operation in Python when schData above is as follows:

>>> type(schData)
Out[N]: pandas.core.series.Series

for regular strings there is the re.sub function but that only seems to work with strings

uday
  • 6,453
  • 13
  • 56
  • 94

2 Answers2

2

http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html

That the type of thing you're looking for?

Python pandas equivalent for replace Has a few little examples.

PS: please include a reproducible example next time =)

Community
  • 1
  • 1
James Tobin
  • 3,070
  • 19
  • 35
  • 1
    Example from [that answer](https://stackoverflow.com/questions/12152716/python-pandas-equivalent-for-replace): create a pandas series `s = pandas.Series(["ape", "monkey", "seagull"])` replace "a" with "x" `s.replace("a", "x", regex=True)` – Paul Rougieux Mar 18 '19 at 14:55
2

Use pandas replace, with the argument regex=True as explained in this answer.

import pandas
s = pandas.Series(["ape", "monkey", "seagull"]) 

replace "a" with "i"

s.replace("a", "i", regex=True)                                                                                                                                             
Out[4]: 
0        ipe
1     monkey
2    seigull
dtype: object
Paul Rougieux
  • 10,289
  • 4
  • 68
  • 110
  • 1
    Hey Paul, I wrote that question 5 years ago, when not only Pandas’ online documentation was limited, but Pandas functionality was lower than it is today. thanks for the effort. Welcome to Pandas! – uday Jun 11 '19 at 16:24
  • I'm moving part of my modeling work from R to pandas, that's why I've been searching for pandas equivalent of `gsub()` and other R functions. – Paul Rougieux Jun 12 '19 at 06:16