簡體   English   中英

從multiindex csv文件創建mulitindex pandas數據框

[英]Create a mulitindex pandas data frame from a multiindex csv file

我正在嘗試從現有的csv文件創建多索引熊貓數據框(最終是一個csv文件)。 我很難遍歷數據幀,因為它包含兩個以上的維。 我該如何完成? 原始的csv文件如下所示:

"Products" "Technologies" Region1 Region2 Region3
Prod1       Tech1         16      0       12
Prod2       Tech2         0       12      22
Prod3       Tech3         22      0       36

我正在尋找創建一個如下所示的csv文件:

"Technologies"  "Regions"   Prod1   Prod2   Prod3
Tech1           Region1     16      0       0
Tech1           Region2     0       0       0
Tech1           Region3     12      0       0
Tech2           Region1     0       0       0
Tech2           Region2     0       12      0
Tech2           Region3     0       22      0
Tech3           Region1     0       0       22
Tech3           Region2     0       0       0
Tech3           Region3     0       0       36

stackunstack是重塑數據幀的有用功能,前者將列索引轉換為行索引,而后者則相反,也可以查看此教程

# transform regions to a separate column
(df.set_index(["Products", "Technologies"]).stack()

# rename the Region column and remove the name for Products column as it will be unstacked
   .rename_axis(("", "Technologies", "Regions"))

# unstack the product column to headers and reset the index to be columns
   .unstack(level=0, fill_value=0).reset_index())

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM