Skip to content
Advertisement

How to handle Pandas columns where elements are Lists?

I have loaded some JSON API data as a Pandas dataframe, as such, there are some columns that come out as lists. I also have some NaN values.

First and foremost I want to replace the NaN with a single word such as ’empty’ but the rest of the data are already in list forms. I want to ultimately create a new column that operates on this list structure and essentially turns it into a string since I will be using the strings to perform mapping logic later on.

Here is some sample data and logic:

JavaScript

Any ideas on how to handle the NaNs in a fashion that makes them still ‘list-like’? I cant perform my lambda function on the column since NaNs are treated like a float.

EDIT: Solution provided by @SimonHawe in the comments. Instead of using fillna at all, the solution is to use if else within the lambda function to handle the NaN case.

SOLUTION:

JavaScript

Advertisement

Answer

IIUC, you can get all the rows with NaN and fill them with ['empty'] which you can then pass through the eval function:

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