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

Time:05-10

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 ?

Thanks

CodePudding user response:

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))

CodePudding user response:

You can try

df['ids'] = df['ids'].apply(lambda x: [[],[],[],[]] if x!=x else x)

This uses the feature that np.nan is not equal with itself.

CodePudding user response:

Try this:

df['ids'] = df['ids'].apply(lambda d: d if d is not np.nan else [[],[],[],[]])
  • Related