Skip to content

BUG, COMPAT: Fix multi-char sep + non-utf8 in read_csv for Python 2 #13812

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

Merged
Merged
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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v0.19.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -788,3 +788,4 @@ Bug Fixes
- Bugs in ``Index.difference`` and ``DataFrame.join`` raise in Python3 when using mixed-integer indexes (:issue:`13432`, :issue:`12814`)

- Bug in ``.to_excel()`` when DataFrame contains a MultiIndex which contains a label with a NaN value (:issue:`13511`)
- Bug in ``pd.read_csv`` in Python 2.x with non-UTF8 encoded, multi-character separated data (:issue:`3404`)
4 changes: 4 additions & 0 deletions pandas/io/parsers.py
Original file line number Diff line number Diff line change
Expand Up @@ -1871,6 +1871,10 @@ class MyDialect(csv.Dialect):
else:
def _read():
line = f.readline()

if compat.PY2 and self.encoding:
line = line.decode(self.encoding)

pat = re.compile(sep)
yield pat.split(line.strip())
for line in f:
Expand Down
16 changes: 16 additions & 0 deletions pandas/io/tests/parser/python_parser_only.py
Original file line number Diff line number Diff line change
Expand Up @@ -201,3 +201,19 @@ def test_skipfooter_with_decimal(self):
result = self.read_csv(StringIO(data), names=['a'],
decimal='#', skipfooter=1)
tm.assert_frame_equal(result, expected)

def test_encoding_non_utf8_multichar_sep(self):
# see gh-3404
expected = DataFrame({'a': [1], 'b': [2]})

for sep in ['::', '#####', '!!!', '123', '#1!c5',
'%!c!d', '@@#4:2', '_!pd#_']:
data = '1' + sep + '2'

for encoding in ['utf-16', 'utf-16-be', 'utf-16-le',
'utf-32', 'cp037']:
encoded_data = data.encode(encoding)
result = self.read_csv(BytesIO(encoded_data),
sep=sep, names=['a', 'b'],
encoding=encoding)
tm.assert_frame_equal(result, expected)