1

Is there a function that can swap between the following dataframes(df1,df2):

import random
import pandas as pd
numbers = random.sample(range(1,50), 10)
d = {'num': list(range(1,6)) + list(range(1,6)),'values':numbers,'type':['a']*5 + ['b']*5}
df = pd.DataFrame(d)

e = {'num': list(range(1,6)) ,'a':numbers[:5],'b':numbers[5:]}
df2 = pd.DataFrame(e)

Dataframe df1:

   #df1
   num type  values
0    1    a      18
1    2    a      26
2    3    a      34
3    4    a      21
4    5    a      48
5    1    b       1
6    2    b      19
7    3    b      36
8    4    b      42
9    5    b      30

Dataframe df2:

    a   b  num
0  18   1    1
1  26  19    2
2  34  36    3
3  21  42    4
4  48  30    5

I take the first df and the type column becomes a type name with the variables.Is there a function that can do this(from df1 to df2) and the vice-verca action(from df2 to df1)

1 Answer 1

3

You can use stack and pivot:

print df
   num type  values
0    1    a      20
1    2    a      25
2    3    a       2
3    4    a      27
4    5    a      29
5    1    b      39
6    2    b      40
7    3    b       6
8    4    b      17
9    5    b      47
print df2
    a   b  num
0  20  39    1
1  25  40    2
2   2   6    3
3  27  17    4
4  29  47    5
df1 = df2.set_index('num').stack().reset_index()
df1.columns = ['num','type','values']
df1 = df1.sort_values('type')
print df1
   num type  values
0    1    a      20
2    2    a      46
4    3    a      21
6    4    a      33
8    5    a      10
1    1    b      45
3    2    b      39
5    3    b      38
7    4    b      37
9    5    b      34

df3 = df.pivot(index='num', columns='type', values='values').reset_index()
df3.columns.name = None
df3 = df3[['a','b','num']]
print df3
    a   b  num
0  46  23    1
1  38   6    2
2  36  47    3
3  33  34    4
4  15   1    5
Sign up to request clarification or add additional context in comments.

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.