简体   繁体   English

如何用 Pandas 中 4 个元素的空列表 [] 填充数据框 Nan 值?

[英]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 [[],[],[],[]].我想用 [[],[],[],[]] 替换Nan 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?对于 1 元素列表效果很好,但是我们如何将它与 4 元素列表一起使用?

您不能将fillna与列表一起使用,但您可以创建一个包含重复数据帧长度的列表的系列,并将其分配给b其中b是 NaN:

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

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.这使用了np.nan与自身不相等的特性。

You can use .apply() checking if the value is np.nan or not.您可以使用.apply()检查该值是否为np.nan 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 [[],[],[],[]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM