2014-10-16 154 views
0

我有一个带有多行索引和多列索引的熊猫数据帧。使用多行索引和多列索引读取和写入Pandas DataFrame

行索引名称:(User_ID,User_Name)。列索引名称:(User_Type,Sample_ID)。

数据框看起来像这样。

In: user_frame.head(2) 

Out: 

     Sample_Type TV TV Radio TV 
     Sample_ID 1 2 3  4 
User_ID User_Name 
1000001 Jim   0.1 0.3 0.5 0.9 
1000001 Julie  0.2 0.9 0.1 0.5 

我想写这个到磁盘。

user_frame.to_csv(fi_path,{write_args}) 

然后用多行和多列索引读回来。

user_frame_new=pd.read_csv(fi_path,{read_args}) 

我还没有找到保留多行和多列索引的正确write_args/read_args。

这样做的正确方法是什么?

由于

回答

0

下面是一个例子:

idx = pd.MultiIndex.from_product([["A", "B"], [1, 2, 3]]) 
col = pd.MultiIndex.from_product([["X", "Y"], ["aa", "bb"]]) 
df = pd.DataFrame(np.random.randint(0, 100, size=(6, 4)), index=idx, columns=col) 
df.index.names = "name1", "name2" 
df.columns.names = "NAME1", "NAME2" 

df.to_csv("tmp.csv") 
df2 = pd.read_csv("tmp.csv", header=[0, 1], index_col=[0, 1])