我認爲這會做
In [3]: df = DataFrame(dict(A = 'foo', B = 'bar', value = 1),index=range(5)).set_index(['A','B'])
In [4]: df
Out[4]:
value
A B
foo bar 1
bar 1
bar 1
bar 1
bar 1
In [5]: df.to_csv('test.csv')
In [6]: !cat test.csv
A,B,value
foo,bar,1
foo,bar,1
foo,bar,1
foo,bar,1
foo,bar,1
In [7]: pd.read_csv('test.csv',index_col=[0,1])
Out[7]:
value
A B
foo bar 1
bar 1
bar 1
bar 1
bar 1
爲了與指數複製寫(一種黑客攻擊的雖然)
In [27]: x = df.reset_index()
In [28]: mask = df.index.to_series().duplicated()
In [29]: mask
Out[29]:
A B
foo bar False
bar True
bar True
bar True
bar True
dtype: bool
In [30]: x.loc[mask.values,['A','B']] = ''
In [31]: x
Out[31]:
A B value
0 foo bar 1
1 1
2 1
3 1
4 1
In [32]: x.to_csv('test.csv')
In [33]: !cat test.csv
,A,B,value
0,foo,bar,1
1,,,1
2,,,1
3,,,1
4,,,1
讀回是有點棘手,其實
In [37]: pd.read_csv('test.csv',index_col=0).ffill().set_index(['A','B'])
Out[37]:
value
A B
foo bar 1
bar 1
bar 1
bar 1
bar 1
''tupleize_cols''用於列上的多索引(它的值爲0.12); (''idxa','idxb'])。to_csv()''是你最好的選擇(指定''index_col = ['idxa','idxb']''讀取-back – Jeff
我給出了一個答案,以便更好地解釋 – Jeff