df.explode() 函数在 python 中不起作用

发布于 2025-01-11 00:02:49 字数 235 浏览 0 评论 0原文

我面临一个奇怪的问题,我在数据框中有一个列名“window”,它有一个值列表,即[3,9,45,78]。我正在尝试使用 df.explode('window') 分解此列,但这没有任何作用。 “window”列的数据类型是对象。 我检查了我的 pandas 版本,它是 - 1.3.4

数据框示例

I am facing a weird issue, I have a column name 'window' in a data frame and it has a list of values i.e., [3,9,45,78]. I am trying to explode this column using df.explode('window') but this is doing no job. datatype of 'window' column is object.
I have checked my pandas version it is - 1.3.4

dataframe example

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

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

发布评论

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

评论(1

﹉夏雨初晴づ 2025-01-18 00:02:49

请记住,df.explode 并没有就地完成其工作。它返回一个包含更改的新数据帧:

import pandas as pd

data = [
    [ 0, [1,2,3], [4,5,6], 7 ],
    [ 0, [1,2,3], [4,5,6], 7 ],
    [ 0, [1,2,3], [4,5,6], 7 ],
    [ 0, [1,2,3], [4,5,6], 7 ],
    [ 0, [1,2,3], [4,5,6], 7 ]
]

df = pd.DataFrame( data, columns=['one', 'two','three','four'] )
print(df)
df2 = df.explode('two')
print(df2)

输出:

   one        two      three  four
0    0  [1, 2, 3]  [4, 5, 6]     7
1    0  [1, 2, 3]  [4, 5, 6]     7
2    0  [1, 2, 3]  [4, 5, 6]     7
3    0  [1, 2, 3]  [4, 5, 6]     7
4    0  [1, 2, 3]  [4, 5, 6]     7
   one two      three  four
0    0   1  [4, 5, 6]     7
0    0   2  [4, 5, 6]     7
0    0   3  [4, 5, 6]     7
1    0   1  [4, 5, 6]     7
1    0   2  [4, 5, 6]     7
1    0   3  [4, 5, 6]     7
2    0   1  [4, 5, 6]     7
2    0   2  [4, 5, 6]     7
2    0   3  [4, 5, 6]     7
3    0   1  [4, 5, 6]     7
3    0   2  [4, 5, 6]     7
3    0   3  [4, 5, 6]     7
4    0   1  [4, 5, 6]     7
4    0   2  [4, 5, 6]     7
4    0   3  [4, 5, 6]     7

Remember that df.explode does not do its work in place. It RETURNS a new dataframe with the changes:

import pandas as pd

data = [
    [ 0, [1,2,3], [4,5,6], 7 ],
    [ 0, [1,2,3], [4,5,6], 7 ],
    [ 0, [1,2,3], [4,5,6], 7 ],
    [ 0, [1,2,3], [4,5,6], 7 ],
    [ 0, [1,2,3], [4,5,6], 7 ]
]

df = pd.DataFrame( data, columns=['one', 'two','three','four'] )
print(df)
df2 = df.explode('two')
print(df2)

Output:

   one        two      three  four
0    0  [1, 2, 3]  [4, 5, 6]     7
1    0  [1, 2, 3]  [4, 5, 6]     7
2    0  [1, 2, 3]  [4, 5, 6]     7
3    0  [1, 2, 3]  [4, 5, 6]     7
4    0  [1, 2, 3]  [4, 5, 6]     7
   one two      three  four
0    0   1  [4, 5, 6]     7
0    0   2  [4, 5, 6]     7
0    0   3  [4, 5, 6]     7
1    0   1  [4, 5, 6]     7
1    0   2  [4, 5, 6]     7
1    0   3  [4, 5, 6]     7
2    0   1  [4, 5, 6]     7
2    0   2  [4, 5, 6]     7
2    0   3  [4, 5, 6]     7
3    0   1  [4, 5, 6]     7
3    0   2  [4, 5, 6]     7
3    0   3  [4, 5, 6]     7
4    0   1  [4, 5, 6]     7
4    0   2  [4, 5, 6]     7
4    0   3  [4, 5, 6]     7
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文