Skip to content
Advertisement

Expand selected keys in a json pandas column

I have this sample dataset:

JavaScript

And I want to ‘expand’ (or ‘explode’) each value in the json column, but only selecting some columns. This is the expected result:

JavaScript

Firstly I tried using json_normalize and iterate over each row (even when the last row has no data), but I have to know before how many rows I’m going to expand:

JavaScript

I only want keys date,amount and name. So I tried this:

JavaScript

But my data frame temp_df needs a reference to the original dataset the_df to apply a merge. Please, could you guide me to the right solution? I guess there must be a way to recall the id, or a method in pandas to do this without a for loop.

Advertisement

Answer

Here are the steps you could follow

(1) define df

JavaScript

(2) explode the column ‘moves’

JavaScript

(3) json_normalize the column ‘moves’

JavaScript

(4) concat the 2 df with only the relevant columns

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