Search code examples
pythonpandasdataframetransposedata-processing

Hi all, I want to transpose my data frame


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.


Solution

  • 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