0

In Python how to convert the following table structure into rows

ID   Manager1    Manager2    Manager3
1    S394[1]       G490[2]     3004[3]
2    3905[1]       4003[2]     5003[3]

Expected Output

    ID   Manager
    1    S394[1]
    1    G490[2]
    1    3004[3]
    2    3905[1] 
    2    4003[2] 
    2    5003[3]

I tried using transpose() and pivot(). Both options did not work

df.pivot(index='SOEID',columns=['Manager1','Manager2','Manager3'])

I also tried pd.melt() I get an error saying index has only 1 level not 2.

df.melt(id_vars='SOEID', var_name=['Manager1','Manager2','Manager3'])
0

2 Answers 2

2

You can use lreshape too:

pd.lreshape(df, {'Manager': ['Manager1', 'Manager2','Manager3']}).sort_values('ID')

Ouput:

   ID  Manager
0   1  S394[1]
2   1  G490[2]
4   1  3004[3]
1   2  3905[1]
3   2  4003[2]
5   2  5003[3]

Note: lreshape is currently undocumented, and it's possible it might be removed.

Sign up to request clarification or add additional context in comments.

Comments

1

Problem is you need value_vars for list of columns names in DataFrame.melt:

df1 = (df.melt(id_vars='ID', 
             value_vars=['Manager1','Manager2','Manager3'], 
             value_name='Manager', 
             var_name='tmp').drop('tmp', axis=1).sort_values('ID'))
 

print (df1)
   ID  Manager
0   1  S394[1]
2   1  G490[2]
4   1  3004[3]
1   2  3905[1]
3   2  4003[2]
5   2  5003[3]

Alternative solution with DataFrame.stack:

df2 = (df.set_index('ID')[['Manager1','Manager2','Manager3']]
         .stack()
         .reset_index(level=1, drop=True)
         .reset_index(name='Manager'))

print (df2)
   ID  Manager
0   1  S394[1]
1   1  G490[2]
2   1  3004[3]
3   2  3905[1]
4   2  4003[2]
5   2  5003[3]

Comments

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.