Home > Back-end >  melt dataframe row by row (like numpy.ndarray.reshape)
melt dataframe row by row (like numpy.ndarray.reshape)

Time:02-21

I have a dataframe

df = pd.DataFrame(dict(x=[1, 2, 3], y=[4, 5, 6]))
    x   y
0   1   4
1   2   5
2   3   6

I want to melt it “row by row”, i.e. in this way:

    var value
0   x   1
1   y   4
2   x   2
3   y   5
4   x   3
5   y   6

but what I get if I do df.melt() is the following:

df.melt()
    var value
0   x   1
1   x   2
2   x   3
3   y   4
4   y   5
5   y   6

I have a solution with .reshape, but it's not very elegant:

pd.DataFrame(
    dict(
         var=list(df.columns) * df.shape[0],
         values=df.values.reshape(-1),
    )
)

Are there any more "native pandas" way to do it?

This question is similiar to that one, but it's not a duplicate: specifically, sorting-based answers there doesn't work for my problem.

CodePudding user response:

Then you can check stack

df.stack().reset_index(level=1)

Or you can fix your code with

df.T.reset_index().melt('index').drop('variable',axis=1)
Out[164]: 
  index  value
0     x      1
1     y      4
2     x      2
3     y      5
4     x      3
5     y      6
  • Related