close

How to fill dataframe Nan values with empty list [] in pandas?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to fill dataframe Nan values with empty list [] in pandas in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to fill dataframe Nan values with empty list [] in pandas?

  1. How to fill dataframe Nan values with empty list [] in pandas?

    I originally tried using pd.isnull (or pd.notnull) but, when given a list, that returns the null-ness of each element.

  2. fill dataframe Nan values with empty list [] in pandas

    I originally tried using pd.isnull (or pd.notnull) but, when given a list, that returns the null-ness of each element.

Method 1

instead tests for list-ness rather than using isnan:

df['ids'] = df['ids'].apply(lambda d: d if isinstance(d, list) else [])

I originally tried using pd.isnull (or pd.notnull) but, when given a list, that returns the null-ness of each element.

Method 2

After a lot of head-scratching I found this method that should be the most efficient (no looping, no apply), just assigning to a slice:

isnull = df.ids.isnull()

df.loc[isnull, 'ids'] = [ [[]] * isnull.sum() ]

The trick was to construct your list of [] of the right size (isnull.sum()), and then enclose it in a list: the value you are assigning is a 2D array (1 column, isnull.sum() rows) containing empty lists as elements.

Conclusion

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read