0

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?

2
  • Is it a string or np.nan? Commented May 9, 2022 at 17:43
  • 1
    it is a np.nan. Commented May 9, 2022 at 17:46

3 Answers 3

2

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))
Sign up to request clarification or add additional context in comments.

Comments

2

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.

1 Comment

Cool to take advantage of that property of NaN. However, apply is necessarily going to be slow.
1

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 [[],[],[],[]])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.