aakash singh
aakash singh

Reputation: 305

Python pandas dataframe transpose and column as index

I have a dataframe say,

    col_a    col_b    col_c    col_d
0    10       A        10       10
1    20       B        20       20
2    30       C        30       30
3    40       D        40       40

I am trying to transpose it to,

       A    B    C    D
col_a 10   20    30  40
col_c 10   20    30  40
col_d 10   20    30  40

Upvotes: 0

Views: 67

Answers (1)

ansev
ansev

Reputation: 30940

Use DataFrame.set_index + DataFrame.transpose:

new_df=df.set_index('col_b').T
print(new_df)

col_b   A   B   C   D
col_a  10  20  30  40
col_c  10  20  30  40
col_d  10  20  30  40

You can remove the name of columns doing:

new_df.columns.name=None
print(new_df)

        A   B   C   D
col_a  10  20  30  40
col_c  10  20  30  40
col_d  10  20  30  40

Also you can use DataFrame.pivot_table:

df.pivot_table(columns='col_b')

col_b   A   B   C   D
col_a  10  20  30  40
col_c  10  20  30  40
col_d  10  20  30  40

Upvotes: 2

Related Questions