Skip to content

.str.replace does not accept a repl function #15055

Closed
@hzpc-joostk

Description

@hzpc-joostk

I wanted to pass a function as repl to .str.replace so it was used by re.sub. But it seems that a bug fix for #13438 prevented that to happen. What are your thoughts about this?

Code Sample

s = pd.Series(['foo', 'bar', 'baz'])
s.str.replace(r'[aeiou]', lambda m: m.group().upper())

Problem description

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-26-bc58c5c60bd2> in <module>()
----> 1 s.str.replace(r'[aeiou]', lambda m: m.group().upper())

/anaconda3/lib/python3.4/site-packages/pandas/core/strings.py in replace(self, pat, repl, n, case, flags)
   1504     def replace(self, pat, repl, n=-1, case=True, flags=0):
   1505         result = str_replace(self._data, pat, repl, n=n, case=case,
-> 1506                              flags=flags)
   1507         return self._wrap_result(result)
   1508 

/anaconda3/lib/python3.4/site-packages/pandas/core/strings.py in str_replace(arr, pat, repl, n, case, flags)
    320     # Check whether repl is valid (GH 13438)
    321     if not is_string_like(repl):
--> 322         raise TypeError("repl must be a string")
    323     use_re = not case or len(pat) > 1 or flags
    324 

TypeError: repl must be a string

Expected Output

0    fOO
1    bAr
2    bAz
dtype: object

Output of pd.show_versions()

INSTALLED VERSIONS
------------------
commit: None
python: 3.4.5.final.0
python-bits: 64
OS: Linux
OS-release: 2.6.32-573.3.1.el6.x86_64
machine: x86_64
processor: x86_64
byteorder: little
LC_ALL: en_US.UTF-8
LANG: en_US.UTF-8
LOCALE: en_US.UTF-8

pandas: 0.19.0
nose: 1.3.7
pip: 9.0.1
setuptools: 18.1
Cython: 0.25.1
numpy: 1.11.1
scipy: 0.17.1
statsmodels: 0.6.1
xarray: None
IPython: 5.0.0
sphinx: 1.3.1
patsy: 0.4.0
dateutil: 2.4.2
pytz: 2015.7
blosc: None
bottleneck: 1.0.0
tables: 3.2.2
numexpr: 2.6.1
matplotlib: 1.5.0
openpyxl: 2.3.2
xlrd: 0.9.4
xlwt: None
xlsxwriter: None
lxml: 3.5.0
bs4: 4.4.1
html5lib: None
httplib2: None
apiclient: None
sqlalchemy: 1.0.14
pymysql: None
psycopg2: 2.6.1 (dt dec pq3 ext)
jinja2: 2.8
boto: 2.38.0
pandas_datareader: None

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugStringsString extension data type and string data

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions