Victor
Victor

Reputation: 17097

Pandas transpose column to row

I have a pandas dataframe like this:

DATE     NAME    INCOME   EXPENSE
201811    XX      100      50

I need it transposed (long format) like this:

DATE     NAME    ATTRIBUTE  ATTRIBUTE_VALUE
201811    XX      INCOME      100
201811    XX      EXPENSE      50

I looked at the pandas transpose function but I am not sure how to go from wide format to long format

Upvotes: 2

Views: 292

Answers (1)

anky
anky

Reputation: 75080

Use pd.melt():

pd.melt(df1,id_vars=['DATE','NAME'],var_name='ATTRIBUTE',value_name='ATTRIBUTE_VALUE')

     DATE NAME ATTRIBUTE  ATTRIBUTE_VALUE
0  201811   XX    INCOME              100
1  201811   XX   EXPENSE               50

Upvotes: 6

Related Questions