shweta kothari
shweta kothari

Reputation: 13

Arrange row data to columnar from one dataframe to other

I have a Dataframe df1 with columns:

[date, class, subject, v1, v2, v3]

I have another datframe df2 like:

date, class, subject, tag, value
d1, c1, s1, v1, z1
d1, c2, s1, v1, z2
d1, c1, s1, v2, z3
d1, c1, s2, v3, z4

Now what I want to achieve is group the df2 based on date, class and subject and then for same group get value of v1, v2 and v3(if any value not available then NULL) and put them in same row in df1.

like this:

date, class, subject, v1, v2, v3
d1, c1, s1, z1, z3, NULL
d1, c1, s2, NULL, NULL, z4
d1, c2, s1, z2, NULL, NULL

I tried to achieve this using group by and agg function, but unable to code it. Could someone please suggest, how to do this?

Upvotes: 1

Views: 40

Answers (1)

Ch3steR
Ch3steR

Reputation: 20659

You can use df.pivot here.

df.pivot(
    index=["date", "class", "subject"], columns="tag", values="value"
).reset_index()


tag date class subject   v1   v2   v3
0     d1    c1      s1   z1   z3  NaN
1     d1    c1      s2  NaN  NaN   z4
2     d1    c2      s1   z2  NaN  NaN

Upvotes: 1

Related Questions