Search code examples
pythonpandasdataframefillna

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


This is my dataframe:

          date                          ids
0     2011-04-23  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,...
1     2011-04-24  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,...
2     2011-04-25  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,...
3     2011-04-26  NaN
4     2011-04-27  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,...
5     2011-04-28  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,...

I want to replace Nan with [[],[],[],[]]. How to do that?

df['ids'].fillna("").apply(list)

Is working well for a 1 element list, but how can we use it with 4 element list?


Solution

  • You can't use fillna with lists, but you can create a Series containing your list repeated for the length of the dataframe, and assign that to the b where b is NaN:

    df.loc[df['b'].isna(), 'b'] = pd.Series([ [[]]*4 ] * len(df))