2

I am trying to put column names for each row in pandas dataframe. To illustrate, my data is like

A | B | C
1 | 4 | 7
2 | 5 | 8
3 | 6 | 9

Trying to convert to :


A 1
A 2
A 3
B 4
B 5
B 6
C 7
C 8

Thank you

gartuns
  • 47
  • 6

2 Answers2

2

Use df.melt:

print(df.melt())

Or use pd.melt:

print(pd.melt(df))

Both reproduce:

  variable  value
0        A      1
1        A      2
2        A      3
3        B      4
4        B      5
5        B      6
6        C      7
7        C      8
8        C      9
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
2

If x is your data-frame like this:

import pandas as pd

x= pd.DataFrame ([[1,4,5],[2,5,8],[3,6,9]])
x.columns = ['A','B','C']
print(x)

   A  B  C
0  1  4  5
1  2  5  8
2  3  6  9

At the first, you should append value of x and columns of x in two separate lists such as a and b:

a = []
b = []

for i in range(0,len(x)):
    for j in range(0,len(x.columns)):
        a.append(x.iloc[i][j])
        b.append(x.columns[j]) 
print(a)
print(b)
[1, 4, 5, 2, 5, 8, 3, 6, 9]
['A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C']

Now a is your list that you want and b is indexes of a. So, you can build your data-frame in this way:

f= pd.DataFrame(a)
f.index=b

If you want to sort it you can try this code:

print(f.sort_index())

A  1
A  2
A  3
B  4
B  5
B  6
C  5
C  8
C  9
Hamed Baziyad
  • 1,954
  • 5
  • 27
  • 40