[英]Read and write Pandas DataFrame with multi-row and multi-column index
我有一個帶有多行和多列索引的熊貓數據框。
行索引名稱:(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。
正確的方法是什么?
謝謝
這是一個例子:
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])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.