s_khan92
s_khan92

Reputation: 979

Need to convert all columns in a row with unique values infront?

I have data frame where i need to convert all the column in a row with their unique values

A       B       C
1       2       2
1       2       3
5       2       9

Desired output

X1   V1
A    1
A    5
B    2
C    2
C    3
C    9

I can get unique values by unique() function but don't know how I get desired output in pandas

Upvotes: 2

Views: 60

Answers (1)

perl
perl

Reputation: 9941

You can use melt and drop_duplicates:

df.melt(var_name='X1', value_name='V1').drop_duplicates()

Output:

  X1  V1
0  A   1
2  A   5
3  B   2
6  C   2
7  C   3
8  C   9

P.S. And you can add .reset_index(drop=True) if you want to have sequential integers for index

Upvotes: 6

Related Questions