Skip to content

Commit 9cbe8b9

Browse files
nbonnottejreback
authored andcommitted
BUG: multi-index to_native_types is not passing thru parameters, #7791
1 parent 1e98c68 commit 9cbe8b9

File tree

4 files changed

+25
-1
lines changed

4 files changed

+25
-1
lines changed

doc/source/whatsnew/v0.17.1.txt

+1
Original file line numberDiff line numberDiff line change
@@ -126,3 +126,4 @@ Bug Fixes
126126

127127

128128
- Bug in the link-time error caused by C ``inline`` functions on FreeBSD 10+ (with ``clang``) (:issue:`10510`)
129+
- Bug in ``DataFrame.to_csv`` in passing through arguments for formatting ``MultiIndexes``, including ``date_format`` (:issue:`7791`)

pandas/core/index.py

+6-1
Original file line numberDiff line numberDiff line change
@@ -4327,7 +4327,12 @@ def _reference_duplicate_name(self, name):
43274327
return sum(name == n for n in self.names) > 1
43284328

43294329
def _format_native_types(self, **kwargs):
4330-
return self.values
4330+
# we go through the levels and format them
4331+
levels = [level._format_native_types(**kwargs)
4332+
for level in self.levels]
4333+
mi = MultiIndex(levels=levels, labels=self.labels, names=self.names,
4334+
sortorder=self.sortorder, verify_integrity=False)
4335+
return mi.values
43314336

43324337
@property
43334338
def _constructor(self):

pandas/tests/test_format.py

+11
Original file line numberDiff line numberDiff line change
@@ -2952,6 +2952,17 @@ def test_to_csv_date_format(self):
29522952
self.assertEqual(df_day.to_csv(), expected_default_day)
29532953
self.assertEqual(df_day.to_csv(date_format='%Y-%m-%d'), expected_default_day)
29542954

2955+
# testing if date_format parameter is taken into account for
2956+
# multi-indexed dataframes (GH 7791)
2957+
df_sec['B'] = 0
2958+
df_sec['C'] = 1
2959+
expected_ymd_sec = 'A,B,C\n2013-01-01,0,1\n'
2960+
df_sec_grouped = df_sec.groupby([pd.Grouper(key='A', freq='1h'), 'B'])
2961+
self.assertEqual(
2962+
df_sec_grouped.mean().to_csv(date_format='%Y-%m-%d'),
2963+
expected_ymd_sec
2964+
)
2965+
29552966
# deprecation GH11274
29562967
def test_to_csv_engine_kw_deprecation(self):
29572968
with tm.assert_produces_warning(FutureWarning):

pandas/tests/test_frame.py

+7
Original file line numberDiff line numberDiff line change
@@ -7341,6 +7341,13 @@ def test_to_csv_quoting(self):
73417341
df.to_csv(buf, encoding='utf-8', index=False)
73427342
self.assertEqual(buf.getvalue(), text)
73437343

7344+
# testing if quoting parameter is passed through with multi-indexes
7345+
# related to issue #7791
7346+
df = pd.DataFrame({'a': [1, 2], 'b': [3, 4], 'c': [5, 6]})
7347+
df = df.set_index(['a', 'b'])
7348+
expected = '"a","b","c"\n"1","3","5"\n"2","4","6"\n'
7349+
self.assertEqual(df.to_csv(quoting=csv.QUOTE_ALL), expected)
7350+
73447351
def test_to_csv_unicodewriter_quoting(self):
73457352
df = DataFrame({'A': [1, 2, 3], 'B': ['foo', 'bar', 'baz']})
73467353

0 commit comments

Comments
 (0)