'melt dataframe row by row (like numpy.ndarray.reshape)

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.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source