Skip to content

Commit 9df1d82

Browse files
committed
FIX: fix multiindex
1 parent 417e74a commit 9df1d82

File tree

1 file changed

+5
-15
lines changed

1 file changed

+5
-15
lines changed

pandas/io/formats/csvs.py

+5-15
Original file line numberDiff line numberDiff line change
@@ -311,42 +311,32 @@ def _save(self) -> None:
311311
self._save_body()
312312

313313
def _save_header(self) -> None:
314-
if any(self.encoded_labels):
314+
if not self.has_mi_columns or self._has_aliases:
315315
self.writer.writerow(self.encoded_labels)
316316
else:
317-
for row in self._get_header_rows():
317+
for row in self._generate_multiindex_header_rows():
318318
self.writer.writerow(row)
319319

320-
def _get_header_rows(self) -> List[List[str]]:
321-
rows = []
322-
323-
# write out the mi
320+
def _generate_multiindex_header_rows(self):
324321
columns = self.obj.columns
325-
326-
# write out the names for each level, then ALL of the values for
327-
# each level
328322
for i in range(columns.nlevels):
329-
330323
# we need at least 1 index column to write our col names
331324
col_line = []
332325
if self.index:
333-
334326
# name is the first column
335327
col_line.append(columns.names[i])
336328

337329
if isinstance(self.index_label, list) and len(self.index_label) > 1:
338330
col_line.extend([""] * (len(self.index_label) - 1))
339331

340332
col_line.extend(columns._get_level_values(i))
341-
rows.append(col_line)
333+
yield col_line
342334

343335
# Write out the index line if it's not empty.
344336
# Otherwise, we will print out an extraneous
345337
# blank line between the mi and the data rows.
346338
if self.encoded_labels and set(self.encoded_labels) != {""}:
347-
rows.append([""] * len(columns))
348-
349-
return rows
339+
yield self.encoded_labels + [""] * len(columns)
350340

351341
def _save_body(self) -> None:
352342
nrows = len(self.data_index)

0 commit comments

Comments
 (0)