Skip to content
Advertisement

Convert one row of a pandas dataframe into multiple rows

I want to turn this:

JavaScript

Into this:

JavaScript

Context: I have data stored with one value coded for all ages (age = 99). However, the application I am developing for needs the value explicitly stated for every id-age pair (id =1, age = 25,50, and 75). There are simple solutions to this: iterate over id’s and append a bunch of dataframes, but I’m looking for something elegant. I’d like to do a many:one merge from my original dataframe to a template containing all the ages, but I would still have to loop over id’s to create the template.

Advertisement

Answer

Don’t know, may be there’s more elegant approach, but you can do something like cross join (or cartesian product):

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