根据列中的条目将数据帧分为多个数据框

发布于 2025-02-10 03:49:03 字数 498 浏览 0 评论 0原文

我有这样的数据框架:

time | text
01.01.2000 | None
None | abc
None | cde
None | def
01.02.2000 | None
None | abb
None | bbc
None | dde
01.03.2000 | None
None | 123
None | 278
None | 782

我现在想在多个数据范围内将此数据框架分开,从时间不是没有时间的值开始,然后在每个原始行之后使用一个新行,为每个数据框架添加一个一个for每个数据帧。这意味着它应该看起来像这样:

df1
time | text
01.01.2000 | abc \n cde \n def

以及这样的第二个数据框架:

df2
time | text
01.02.2000 | abb \n bbc \n dde

我该怎么做?我想使用for循环来做到这一点。

I have such a dataframe:

time | text
01.01.2000 | None
None | abc
None | cde
None | def
01.02.2000 | None
None | abb
None | bbc
None | dde
01.03.2000 | None
None | 123
None | 278
None | 782

I now want to split this dataframe in multiple dataframes beginning with the value where time is not None and adding the rows for each dataframe just one after another with a new line after each original row. That means it should look like this:

df1
time | text
01.01.2000 | abc \n cde \n def

And the second dataframe like this:

df2
time | text
01.02.2000 | abb \n bbc \n dde

How can I do this? I would like to use a for loop to do this.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

濫情▎り 2025-02-17 03:49:03

您可以转发填充<代码>时间列,然后groupby 时间

df['time'] = df['time'].ffill()
out = (df.groupby('time', as_index=False)
       ['text'].agg(lambda x: '\n'.join(x.dropna())))
print(out)

         time           text
0  01.01.2000  abc\ncde\ndef
1  01.02.2000  abb\nbbc\ndde
2  01.03.2000  123\n278\n782
groups = [g for name, g in out.groupby('time')]
print(groups)

[         time           text
0  01.01.2000  abc\ncde\ndef,          time           text
1  01.02.2000  abb\nbbc\ndde,          time           text
2  01.03.2000  123\n278\n782]

You can forward fill time column then groupby time column

df['time'] = df['time'].ffill()
out = (df.groupby('time', as_index=False)
       ['text'].agg(lambda x: '\n'.join(x.dropna())))
print(out)

         time           text
0  01.01.2000  abc\ncde\ndef
1  01.02.2000  abb\nbbc\ndde
2  01.03.2000  123\n278\n782
groups = [g for name, g in out.groupby('time')]
print(groups)

[         time           text
0  01.01.2000  abc\ncde\ndef,          time           text
1  01.02.2000  abb\nbbc\ndde,          time           text
2  01.03.2000  123\n278\n782]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文