如何用熊猫中4个元素的空列表填充dataframe nan值?
这是我的数据框架:
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,...
我想将nan
替换为[[],[],[],[]]。怎么做?
df['ids'].fillna("").apply(list)
对于1个元素列表而言,工作良好,但是我们如何将其与4个元素列表一起使用?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不能与列表一起使用
fillna
,但是可以创建一个包含数据框架长度的列表的系列,并将其分配给b
其中> b
是nan: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 theb
whereb
is NaN:您可以尝试
使用
np.nan
与自身不相等的功能。You can try
This uses the feature that
np.nan
is not equal with itself.您可以使用
.apply()
检查该值是否为np.nan
。如果是,请填写嵌套列表,否则正常值。尝试以下操作:
You can use
.apply()
checking if the value isnp.nan
or not. If yes, then fill the nested list otherwise the normal value.Try this: