如何用熊猫中4个元素的空列表填充dataframe nan值?

发布于 2025-01-27 21:19:40 字数 599 浏览 5 评论 0原文

这是我的数据框架:

          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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

荭秂 2025-02-03 21:19:40

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

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

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))
魂归处 2025-02-03 21:19:40

您可以尝试

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

使用np.nan与自身不相等的功能。

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.

梦巷 2025-02-03 21:19:40

您可以使用.apply()检查该值是否为np.nan。如果是,请填写嵌套列表,否则正常值。

尝试以下操作:

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

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 [[],[],[],[]])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文