I am trying to create a multi-index pandas data frame (ultimately a csv file) from an existing csv file. I am having a hard time iterating over data frame because it contains more than 2 dimensions. How do I accomplish this? The original csv file looks like the following:
"Products" "Technologies" Region1 Region2 Region3
Prod1 Tech1 16 0 12
Prod2 Tech2 0 12 22
Prod3 Tech3 22 0 36
And I am looking to create a csv file which looks like this:
"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
stack
and unstack
are helpful functions for reshaping data frame, the former transform the column index to row index and the latter does the opposite, also check this tutorial :
# 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())
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.