Thomas LESIEUR
Thomas LESIEUR

Reputation: 427

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?

Upvotes: 0

Views: 1003

Answers (3)

user17242583
user17242583

Reputation:

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

Upvotes: 2

Abhyuday Vaish
Abhyuday Vaish

Reputation: 2379

You can use .apply() checking if the value is np.nan or not. If yes, then fill the nested list otherwise the normal value.

Try this:

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

Upvotes: 1

Ynjxsjmh
Ynjxsjmh

Reputation: 30032

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.

Upvotes: 2

Related Questions