Skip to content

PERF: Improved performance for .str.encode/decode #13008

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions doc/source/whatsnew/v0.18.1.txt
Original file line number Diff line number Diff line change
Expand Up @@ -412,6 +412,8 @@ Performance Improvements

- Improved performance of ``DataFrame.to_sql`` when checking case sensitivity for tables. Now only checks if table has been created correctly when table name is not lower case. (:issue:`12876`)
- Improved performance of ``Period`` construction and plotting of ``Period``s. (:issue:`12903`, :issue:`11831`)
- Improved performance of ``.str.encode()`` and ``.str.decode()`` methods




Expand Down
22 changes: 20 additions & 2 deletions pandas/core/strings.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,14 @@
import pandas.lib as lib
import warnings
import textwrap
import codecs

_cpython_optimized_encoders = (
"utf-8", "utf8", "latin-1", "latin1", "iso-8859-1", "mbcs", "ascii"
)
_cpython_optimized_decoders = _cpython_optimized_encoders + (
"utf-16", "utf-32"
)

_shared_docs = dict()

Expand Down Expand Up @@ -1182,7 +1190,12 @@ def str_decode(arr, encoding, errors="strict"):
-------
decoded : Series/Index of objects
"""
f = lambda x: x.decode(encoding, errors)
if encoding in _cpython_optimized_decoders:
#CPython optimized implementation
f = lambda x: x.decode(encoding, errors)
else:
decoder = codecs.getdecoder(encoding)
f = lambda x: decoder(x, errors)[0]
return _na_map(f, arr)


Expand All @@ -1200,7 +1213,12 @@ def str_encode(arr, encoding, errors="strict"):
-------
encoded : Series/Index of objects
"""
f = lambda x: x.encode(encoding, errors)
if encoding in _cpython_optimized_encoders:
#CPython optimized implementation
f = lambda x: x.encode(encoding, errors)
else:
encoder = codecs.getencoder(encoding)
f = lambda x: encoder(x, errors)[0]
return _na_map(f, arr)


Expand Down