Skip to content
Advertisement

Create a Nested list from a pandas data frame

I am trying to create a kind of nested list from a pandas data frame.

I have this data frame:

JavaScript

So I want to create a kind of nested list using the above data frame using ‘id1’ column, and ‘Name1’ and ‘Name2’ columns. For example, if we think about the first row, id1 should be in one list ([‘ab-85643’]) and ‘Name1’ and ‘Name2’ should be another list ([‘aasd1′,’vaasd1’]). Then for the 1st row, id1 list and ‘Name1’ and ‘Name2’ list should be in the same list ([[‘aasd1′,’vaasd1’],[‘ab-85643’]]). Some rows doesn’t have “Name” or “Name2”. This should need to be done for all the rows and the final list should be just like the below one.

JavaScript

Is it possible to create that using python?

Can someone give me an idea, please?

Anything is appreciated. Thanks in advance!

Advertisement

Answer

It’s easier if you apply a custom function to the relevant columns:

JavaScript

Output:

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