Skip to content
Advertisement

Pandas – take multiple columns and transform them into a single column of dictionary objects?

I am trying to transform a DataFrame by combining extra columns into a dictionary.

my DataFrame will always have four columns, at least: record, yhat, residual, and hat, with additional columns in different cases. My current df head looks like this:

JavaScript

If we look at the top column, we see that there are 2 additional columns, RinvRes and AOMstat

JavaScript

I would like to combine those columns into a dictionary, where the column name is a key in a dictionary, eg :

JavaScript

Advertisement

Answer

in one step with .join, .agg(dict) and .drop

first create your list of aggregate columns

JavaScript

print(df1)

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