2020-10-29

Pandas Groupby Multiindex for multiple columns [duplicate]

How do you switch the format of a dataframe from a standard single row to multi-index columns? I've tried playing with groupby but it doesn't seem efficient.

+------------+----------+--------+----------+--------+
|  Product   |   Item   | Region | In Stock | Colour |
+------------+----------+--------+----------+--------+
| Electronic | Phone    | Canada | Y        | Black  |
| Electronic | Computer | Canada | N        | Silver |
| Furniture  | Table    | Canada | Y        | Brown  |
| Furniture  | Chair    | Canada | Y        | Black  |
| Electronic | Phone    | USA    | Y        | Black  |
| Electronic | Computer | USA    | Y        | Black  |
| Furniture  | Table    | USA    | N        | Black  |
| Furniture  | Chair    | USA    | Y        | Black  |
| Furniture  | Couch    | USA    | Y        | Black  |
+------------+----------+--------+----------+--------+

to

+------------+----------+----------+--------+----------+--------+
|            |          |       Canada      |         USA       |
+  Product   +   Item   +----------+--------+----------+--------+
|            |          | In Stock | Colour | In Stock | Colour |
+------------+----------+----------+--------+----------+--------+
| Electronic | Phone    | Y        | Black  | Y        | Black  |
|            | Computer | N        | Silver | Y        | Black  |
| Furniture  | Table    | Y        | Brown  | N        | Black  |
|            | Chair    | Y        | Black  | Y        | Black  |
|            | Couch    |          |        | Y        | Black  |
+------------+----------+----------+--------+----------+--------+

Thanks!



from Recent Questions - Stack Overflow https://ift.tt/2Gbkbdy
https://ift.tt/eA8V8J

No comments:

Post a Comment