Skip to content

Fix df.to_csv() for string arrays when encoded in utf-8 #18013

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 3 commits into from
Nov 7, 2017
Merged
Changes from 2 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
26 changes: 25 additions & 1 deletion pandas/tests/io/formats/test_to_csv.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ def test_to_csv_date_format(self):
expected_ymd_sec)

def test_to_csv_multi_index(self):
# see gh-6618
# GH 6618
df = DataFrame([1], columns=pd.MultiIndex.from_arrays([[1], [2]]))

exp = ",1\n,2\n0,1\n"
Expand All @@ -223,3 +223,27 @@ def test_to_csv_multi_index(self):

exp = "foo\nbar\n1\n"
assert df.to_csv(index=False) == exp

def test_to_csv_string_array(self):
# GH 10813
str_array = [{'names': ['foo', 'bar']}, {'names': ['baz', 'qux']}]
df = pd.DataFrame(str_array)
expected_ascii = '''\
,names
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

so if you make this 2 test functions, then you can xfail the non-working one (to at least get things passing)

0,"['foo', 'bar']"
1,"['baz', 'qux']"
'''
with tm.ensure_clean('str_test.csv') as path:
df.to_csv(path, encoding='ascii')
with open(path, 'r') as f:
assert f.read() == expected_ascii

expected_utf8 = '''\
,names
0,"[u'foo', u'bar']"
1,"[u'baz', u'qux']"
'''
with tm.ensure_clean('unicode_test.csv') as path:
df.to_csv(path, encoding='utf-8')
with open(path, 'r') as f:
assert f.read() == expected_utf8