Convert Pandas DataFrame into 2 columns [duplicate]
I have a Pandas DataFrame like so:
| A | B | C |
0 | 3 | e | w |
1 | 4 | f | x |
2 | 5 | g | y |
3 | 6 | h | z |
I'm trying to convert the DataFrame into a two-column structure that preserves the index value, like so:
0 | 3 |
0 | e |
0 | w |
1 | 4 |
1 | f |
1 | x |
2 | 5 |
2 | g |
2 | y |
3 | 6 |
3 | h |
3 | z |
I've tried using df.melt
but it doesn't seem to do what I need. Thanks in advance for any help.
You can use stack
:
df.stack().reset_index(level=1,drop=True) # df.stack().droplevel(1)
0 3
0 e
0 w
1 4
1 f
1 x
2 5
2 g
2 y
3 6
3 h
3 z
Yes you can use melt
with sort_index
:
>>> df.melt(ignore_index=False).sort_index()['value']
0 3
0 e
0 w
1 4
1 f
1 x
2 5
2 g
2 y
3 6
3 h
3 z
Name: value, dtype: object
Or with stack
:
>>> df.stack().droplevel(1)
0 3
0 e
0 w
1 4
1 f
1 x
2 5
2 g
2 y
3 6
3 h
3 z
dtype: object