Pandas Pivot 重复索引行

Leo*_*Leo 3 python pivot pandas

如果我将 Pandas 数据透视表导出到 CSV 表,我会得到

first  second   
bar    one     A    0.721555
               B   -0.706771
       two     A   -1.039575
               B    0.271860
baz    one     A   -0.424972
               B    0.567020
       two     A    0.276232
               B   -1.087401
Run Code Online (Sandbox Code Playgroud)

因为我正在 Excel 中处理这些数据,所以我会重复所有行,例如

first  second   
bar    one     A    0.721555
bar    one     B   -0.706771
bar    two     A   -1.039575
bar    two     B    0.271860
baz    one     A   -0.424972
baz    one     B    0.567020
baz    two     A    0.276232
baz    two     B   -1.087401
Run Code Online (Sandbox Code Playgroud)

你知道这怎么可能吗?

jez*_*ael 5

MultiIndex您可以从by创建列reset_index,然后不通过参数写入默认索引index=False

df = df.reset_index()
df.to_csv(file, index=False)
Run Code Online (Sandbox Code Playgroud)