diff --git a/pandas/_libs/parsers.pyx b/pandas/_libs/parsers.pyx index 82e9812094af2..afce66391de80 100644 --- a/pandas/_libs/parsers.pyx +++ b/pandas/_libs/parsers.pyx @@ -746,7 +746,8 @@ cdef class TextReader: is not None else 0) # if wrong number of blanks or no index, not our format - if (lc != unnamed_count and lc - ic > unnamed_count) or ic == 0: + if ((lc != unnamed_count and lc - ic >= unnamed_count) or + ic == 0): hr -= 1 self.parser_start -= 1 this_header = [None] * lc diff --git a/pandas/tests/io/formats/test_to_csv.py b/pandas/tests/io/formats/test_to_csv.py index 0db49a73621ea..0a16f2d643695 100644 --- a/pandas/tests/io/formats/test_to_csv.py +++ b/pandas/tests/io/formats/test_to_csv.py @@ -332,6 +332,24 @@ def test_to_csv_float_ea_no_float_format(self): ) assert result == expected + def test_to_csv_multi_index_nan(self): + # Create a MultiIndex DataFrame + columns = pd.MultiIndex.from_tuples( + [("Level 1", "Level 2")], names=["level1", "level2"] + ) + data = [[np.nan], [0.1], [0.4]] + df_complex = DataFrame(data, columns=columns) + + # Expected DataFrame + expected_df = DataFrame(data, columns=columns, index=range(3)) + + # Save and load the DataFrame as a CSV + with tm.ensure_clean("complex_data.csv") as path: + df_complex.to_csv(path) + loaded_df_complex = pd.read_csv(path, header=[0, 1], index_col=0) + + tm.assert_frame_equal(loaded_df_complex, expected_df) + def test_to_csv_multi_index(self): # see gh-6618 df = DataFrame([1], columns=pd.MultiIndex.from_arrays([[1], [2]]))