I want to save a pandas pivot table for human reading, but DataFrame.to_csv
doesn't include the DataFrame.columns.name
. How can I do that?
Example:
For the following pivot table:
>>> import pandas as pd
>>> df = pd.DataFrame([[1, 2, 3], [6, 7, 8]])
>>> df.columns = list("ABC")
>>> df.index = list("XY")
>>> df
A B C
X 1 2 3
Y 6 7 8
>>> p = pd.pivot_table(data=df, index="A", columns="B", values="C")
When viewing the pivot table, we have both the index name ("A"), and the columns name ("B").
>>> p
B 2 7
A
1 3.0 NaN
6 NaN 8.0
But when exporting as a csv we lose the columns name:
>>> p.to_csv("temp.csv")
===temp.csv===
A,2,7
1,3.0,
6,,8.0
How can I get some kind of human-readable output format which contains the whole of the pivot table, including the .columns.name
("B")?
Something like this would be fine:
B,2,7
A,,
1,3.0,
6,,8.0
.xls
, not including the "B". – Carminacarminativep.to_csv('temp.csv', index_label=[p.index.name, p.columns.name])
? – Outpouring