在多列上爆炸pandas dataframe

发布于 2025-02-03 01:17:28 字数 449 浏览 1 评论 0原文

我正在尝试基于多个数据范围(在该列中任何地方都有逗号的情况下的情况下,在一个逗号上爆炸),但是当我尝试多个列时,最终会遇到错误。 我尝试了split(),爆炸()

”描述在这里“

预期输出:

I am trying to explode a dataframe based on multiple dataframes (infact on a condition where there is a comma in the data anywhere in that column), but end up getting errors when I try on multiple columns.
I have tried split(), explode() etc.

Input
enter image description here

Expected output:
enter image description here

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

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

发布评论

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

评论(1

贩梦商人 2025-02-10 01:17:28
def pad_list(lst, max_len):
    return lst + [lst[-1]] * (max_len - len(lst))

new_df = df.apply(lambda row: row.apply(lambda item: pad_list(item.split(','), max(row.str.contains(',') + 1))), axis=1).explode(df.columns.tolist())

输出:

>>> new_df
    Cat1   Cat2    Cat3    Cat4    Cat5
0    Cat  table     Pen  Toyota  Sydney
0    Cat  chair     Pen   Honda   Perth
1  Horse  Stand  Pencil  Holden    Bali
1  Horse  Stand  eraser  Holden    Bali
def pad_list(lst, max_len):
    return lst + [lst[-1]] * (max_len - len(lst))

new_df = df.apply(lambda row: row.apply(lambda item: pad_list(item.split(','), max(row.str.contains(',') + 1))), axis=1).explode(df.columns.tolist())

Output:

>>> new_df
    Cat1   Cat2    Cat3    Cat4    Cat5
0    Cat  table     Pen  Toyota  Sydney
0    Cat  chair     Pen   Honda   Perth
1  Horse  Stand  Pencil  Holden    Bali
1  Horse  Stand  eraser  Holden    Bali
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文