Home > Software engineering >  Hi all, I want to transpose my data frame
Hi all, I want to transpose my data frame

Time:11-04

data={'id':[1, 2, 3],'A': ['edx',None , 'edx'],'B': [None,'com',None ],'C': ['tab','tab',None ] }  
df = pd.DataFrame(data)  

Given data frame :

id  A   B   C
1   edx None    tab
2   None    com tab
3   edx None    None

Desired Result:

id  Learn
1   edx
1   tab
2   com
2   tab
3   edx

Same I Expect that I have mentioned above.

CodePudding user response:

Try this. I would really suggest getting familiar with pd.melt as it's extremely useful in reshaping data that looks like this.

df = (df.melt(id_vars='id', value_name='Learn')
        .dropna()
        .sort_values(by='id', ascending='True'))
    
df.drop(columns=['variable'], inplace=True)
print(df)

Output

   id Learn
0   1   edx
6   1   tab
4   2   com
7   2   tab
2   3   edx

CodePudding user response:

here is one way to do it. using stack

out=(df.set_index('id')     # set index
     .stack()               # stack
     .droplevel(1)          # remove the unwanted level
     .reset_index()
     .rename(columns={0:'Learn'}))
out
    id  Learn
0   1   edx
1   1   tab
2   2   com
3   2   tab
4   3   edx
  • Related