7

I have below dataframe and want to transpose the columns aftr 3rd column into rows. Please help on this.

df:
country year    perc    data1   data2   data3
IN      2015    hjk     75      81      96
US      2015    KTM     100     289     632

Results:                
country year    perc    TransposedColumn    Value   
IN      2015    hjk     data1               75  
IN      2015    hjk     data2               81  
IN      2015    hjk     data3               96  
US      2015    KTM     data1               100 
US      2015    KTM     data2               289 
US      2015    KTM     data3               632 
2
  • It would be nice to see what you currently have in your code and where you would like the transpose implementation to be. Could you add this? Commented Jun 21, 2017 at 14:25
  • @EastonBornemeier I have checked post: stackoverflow.com/questions/42292986/… , but its giving error for me... Commented Jun 21, 2017 at 14:27

1 Answer 1

20

use melt:

df.melt(id_vars=['country','year','perc'])

older versions of Pandas:

pd.melt(df, id_vars=['country','year','perc'])

Output:

  country  year perc variable  value
0      IN  2015  hjk    data1     75
1      US  2015  KTM    data1    100
2      IN  2015  hjk    data2     81
3      US  2015  KTM    data2    289
4      IN  2015  hjk    data3     96
5      US  2015  KTM    data3    632

Option #2

df.set_index(['country','year','perc']).stack().reset_index()

Output:

  country  year perc level_3    0
0      IN  2015  hjk   data1   75
1      IN  2015  hjk   data2   81
2      IN  2015  hjk   data3   96
3      US  2015  KTM   data1  100
4      US  2015  KTM   data2  289
5      US  2015  KTM   data3  632
Sign up to request clarification or add additional context in comments.

7 Comments

thanks, but getting error: AttributeError: 'DataFrame' object has no attribute 'melt', using 2.7 python
YOu are using a older version upgarde or pd.melt(df,id_vars=['country','year','perc'])
thanks a lot... working fine... OK.. I will upgrade to latest
how to insert these results to already created data frame 'resultsAll' with same structure, I want to transpose 400+ csv file and insrert to one dataframe, how to achieve this?
df1 = then statement this will assign the results to the df1 variable creating a new dataframe.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.