keshaw
keshaw

Reputation: 1365

Transpose of csv file

I have a csv file in which data is like this

col1,col2,col3,col4,col5
 A,1,3,5,6
 B,2,3,4,5

I want to transpose of this file like this:

col1,col6,col7
 A,Col1,1
 A,col2,3
 A,col3,5

I am using python 2.7. So can I do it using python pandas ?

Upvotes: 0

Views: 227

Answers (1)

Scott Boston
Scott Boston

Reputation: 153460

Use melt:

df.melt(id_vars='col1', var_name='col6', value_name='col7')

Output:

  col1  col6  col7
0    A  col2     1
1    B  col2     2
2    A  col3     3
3    B  col3     3
4    A  col4     5
5    B  col4     4
6    A  col5     6
7    B  col5     5

Option 2 use set_index and stack:

df.set_index('col1').rename_axis('col6', 1).stack().reset_index(name='col7')

Output:

  col1  col6  col7
0    A  col2     1
1    A  col3     3
2    A  col4     5
3    A  col5     6
4    B  col2     2
5    B  col3     3
6    B  col4     4
7    B  col5     5

Upvotes: 6

Related Questions