0

I have a pandas dataframe with a structure like:

| id | (A, dog) | (A,cat) | (B, dog) | (B, cat) |
|---:|---------:|--------:|---------:|----------|
|  1 |        1 |       2 |        3 |          |
|  2 |        4 |       5 |        6 |          |
|  3 |        7 |       8 |        9 |          |

which df.columns = Index([(A, dog) (A,cat), (B, dog),(B, cat)])

And I would like to transform it into:

|    | A         | B         |
| id | dog | cat | dog | cat |
|----|-----|-----|-----|-----|
|  1 |   1 |   2 |   3 |     |
|  2 |   4 |   5 |   6 |     |
|  3 |   7 |   8 |   9 |     |

with df.columns = MultiIndex([(A, dog) (A,cat), (B, dog),(B, cat)])

How can I do that?

I've tried with pd.set_index

  • What about the `id` column? Is that actually the index? Please post some code that reproduces this df. For reference see [How to make good reproducible pandas examples](/q/20109391/4518341) and [mre]. – wjandrea Mar 09 '23 at 18:48
  • BTW, welcome to Stack Overflow! Check out the [tour], and [ask] if you want more tips. – wjandrea Mar 09 '23 at 18:49
  • I've closed your question since it seems to be a duplicate, but LMK if not. – wjandrea Mar 09 '23 at 19:02

0 Answers0