Skip to content
Advertisement

Pivot and merge two pandas dataframes

I have two dataframes (taken from pd.to_clipboard(), suggest using pd.read_clipboard())

df_a:

JavaScript

and df_b:

JavaScript

What I am looking to do is add a third column to df_a, say ThirdVal, which contains the value in df_b where the DateField and Team align. My issue is that df_b is transposed and formatted awry compared to df_a.

I have looked into pd.pivot() but have been unsuccessful in pivoting the dataframe to make it joinable, but I am not sure what to fill in for the columns argument. Should I be looking into a different function?

Advertisement

Answer

What you’re looking for is not pivot, but melt.

JavaScript

Or, for a more general approach, where all columns not specified in id_vars will be used as value_vars:

JavaScript

Gives you a DataFrame looking like this:

JavaScript

Which you can then merge with your df_a:

JavaScript

To get output (not missing values are due to left join as I wanted to preserve df_a data, since you mentioned adding a column to it):

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement