-1

I have the following Dataframe:

df:

enter image description here

And I need to create a DataFrame like this:

df2:

enter image description here

I think that it could be done using a pivot table, but im not sure how to do that.

Or there is a better way to accomplish that task?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Aragorn64
  • 149
  • 7
  • 1
    Does this answer your question? [How do I melt a pandas dataframe?](https://stackoverflow.com/questions/68961796/how-do-i-melt-a-pandas-dataframe) – BigBen Oct 06 '22 at 17:55
  • 1
    You can use melt: ```pd.melt(df, value_vars=["e", "f", "g", "h"], ignore_index=False)``` – dermen Oct 06 '22 at 18:06
  • [Please don't post pictures of text](https://meta.stackoverflow.com/q/285551/4518341). Instead, copy the text itself, [edit] it into your post, and use the formatting tools like [code formatting](/editing-help#code). – wjandrea Oct 06 '22 at 18:17
  • That title is really vague, and there's no actual filtering involved here. Please [edit] to clarify it. I'm thinking, "How can I make the columns of a dataframe the second level of the index?" (assuming that's what you want) – wjandrea Oct 06 '22 at 18:25
  • Oh, actually, is "abcd" the index, or is supposed to represent a column? Please provide a [reproducible pandas example](/q/20109391/4518341) – wjandrea Oct 06 '22 at 18:48

1 Answers1

0

You can use stack

df = df.stack().reset_index().rename(columns={"level_0": 0, "level_1": 1, 0: 2})
print(df)

    0  1   2
0   a  e   1
1   a  f   2
2   a  g   3
3   a  h   4
4   b  e   5
5   b  f   6
6   b  g   7
7   b  h   8
8   c  e   9
9   c  f  10
10  c  g  11
11  c  h  12
12  d  e  13
13  d  f  14
14  d  g  15
15  d  h  16
Jason Baker
  • 3,170
  • 2
  • 12
  • 15