Reputation: 37
Sorry my question is not really clear from the title but what I'm trying to do is exactly this with pandas from this:
col1 col2 col3 col 4
A D G X
B E H Y
C F I Z
to this
col col 4
A X
B Y
C Z
D X
E Y
F Z
G X
H Y
I Z
Upvotes: 0
Views: 38
Reputation: 1624
Try this:
df.melt(id_vars='col4', value_vars=['col1', 'col2', 'col3']).drop(columns='variable')
Output:
col value
0 X A
1 Y B
2 Z C
3 X D
4 Y E
5 Z F
6 X G
7 Y H
8 Z I
Upvotes: 1
Reputation: 23217
You can use df.melt()
as follows:
df.melt(id_vars='col4', value_name='col').drop('variable', axis=1)
Output:
col4 col
0 X A
1 Y B
2 Z C
3 X D
4 Y E
5 Z F
6 X G
7 Y H
8 Z I
Upvotes: 2
Reputation: 68
out_df = pd.DataFrame() out_df['col'] = df['col1'].tolist() + df['col2'].tolist() + df['col3'].tolist()
out_df['col 4'] = df['col 4'].tolist() * 3
Upvotes: 0