user10835913
user10835913

Reputation:

How to reshape the dataframe and transform columns as rows?

df = pd.DataFrame({'ProdcutID': {0: '2125',1: '1204',2: '4390'},
          'Color':{0:'R',1:'B',2:'Y'},
          'From':{0:'CA',1:'OH',2:'IN'},
         'Color1':{0:'P',2:'W'},
         'From1':{0:'NJ',2:'DE'},
         'Color3':{1:'G',2:'P'},
         'From3':{1:'MX',2:'PA'}})

enter image description here

I have above weird dataframe and want to transform the columns into rows. I tried to use df.T but didn't get what I want. Probably use df.groupby('ProductID')...?

Expected results:

enter image description here

Upvotes: 2

Views: 42

Answers (1)

Scott Boston
Scott Boston

Reputation: 153460

Try this using pd.wide_to_long, but first you need to rename a couple of column headers to match the pattern of rest of the columns.

df1 = df.rename(columns={'Color':'Color0','From':'From0'})
pd.wide_to_long(df1,['Color','From'],'ProdcutID','No').sort_index(level=0).dropna()

Output:

             Color From
ProdcutID No           
1204      0      B   OH
          3      G   MX
2125      0      R   CA
          1      P   NJ
4390      0      Y   IN
          1      W   DE
          3      P   PA

Upvotes: 2

Related Questions