首页  >  文章  >  后端开发  >  当行数不能被部分数整除时,如何将大型 Pandas DataFrame 分成相等的部分?

当行数不能被部分数整除时,如何将大型 Pandas DataFrame 分成相等的部分?

Mary-Kate Olsen
Mary-Kate Olsen原创
2024-10-28 03:29:30846浏览

How do I split a large Pandas DataFrame into equal parts when the number of rows is not divisible by the number of parts?

将大型 Pandas 数据帧分割成相等的部分

在 Pandas 中处理大型数据集时,通常需要将它们分成更小的块处理或分析。分割数据帧的一种常用方法是 np.split,它将数据沿指定轴分布到相等数量的数组中。但是,尝试使用此方法拆分奇数行可能会导致 ValueError。

使用 np.array_split 的替代方法

要解决此问题,请考虑使用改为 np.array_split。此函数允许对数据帧进行不等划分,如以下 Python 代码所示:

<code class="python">import pandas as pd
import numpy as np

df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo'],
                    'B' : ['one', 'one', 'two', 'three', 'two', 'two', 'one', 'three'],
                    'C' : np.random.randn(8), 'D' : np.random.randn(8)})

print(df)

split_data = np.array_split(df, 4)

for part in split_data:
    print(part)</code>

此代码的输出显示数据帧被分成四个相等的部分:

     A      B         C         D
0  foo    one -0.174067 -0.608579
1  bar    one -0.860386 -1.210518
2  foo    two  0.614102  1.689837
3  bar  three -0.284792 -1.071160
4  foo    two  0.843610  0.803712
5  bar    two -1.514722  0.870861
6  foo    one  0.131529 -0.968151
7  foo  three -1.002946 -0.257468

     A      B         C         D
0  foo    one -0.174067 -0.608579
1  bar    one -0.860386 -1.210518
2  foo    two  0.614102  1.689837
3  bar  three -0.284792 -1.071160
4  foo    two  0.843610  0.803712
5  bar    two -1.514722  0.870861

     A      B         C         D
0  foo    one  0.131529 -0.968151
1  foo  three -1.002946 -0.257468

     A      B         C         D
0  bar    one -0.860386 -1.210518
1  foo    two  0.614102  1.689837
2  bar  three -0.284792 -1.071160
3  foo    two  0.843610  0.803712
4  bar    two -1.514722  0.870861

使用 np.array_split 可确保数据帧行的均匀分布,无论其总计数如何。这提供了一种将大型数据集分割成可管理的块以进行进一步处理的便捷方法。

以上是当行数不能被部分数整除时,如何将大型 Pandas DataFrame 分成相等的部分?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn