Skip to content

ENH: Add option to keep index in pd.melt #35069

Closed
@erfannariman

Description

@erfannariman

When melting a dataframe, there's no option to keep the original index. This can be beneficial for example when users want to do different kind ravel than the deault F (Fortran style) right now. To make this more clear, see example:

df = pd.DataFrame({'A': [1, 4],
                   'B': [2, 5],
                   'C': [3, 6]})
print(df)
   A  B  C
0  1  2  3
1  4  5  6

print(df.melt())
  variable  value
0        A      1
1        A      4
2        B      2
3        B      5
4        C      3
5        C      6

But the expected output can be row wise instead:

  variable  value
0        A      1
1        B      2
2        C      3
3        A      4
4        B      5
5        C      6

Solution proposal
This could be solved by adding an ignore_index argument which is True by default, but if it is set to False, the result would come out like:

  variable  value
0        A      1
1        A      4
0        B      2
1        B      5
0        C      3
1        C      6

This way the user can sort the index themself and achieve the same result:

print(df.sort_index())
  variable  value
0        A      1
0        B      2
0        C      3
1        A      4
1        B      5
1        C      6

Also in pandas/core/reshape/melt there is an # TODO: what about the existing index? in the melt function. This might solve that TODO if I'm not mistaken.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions