首頁  >  文章  >  後端開發  >  如何將大型 Pandas DataFrame 分成相等的部分?

如何將大型 Pandas DataFrame 分成相等的部分?

Patricia Arquette
Patricia Arquette原創
2024-10-27 08:32:03313瀏覽

How to Split a Large Pandas DataFrame into Equal Parts?

分割大型 Pandas DataFrame

考慮一個由 423244 行組成的大型 Pandas DataFrame。需要將此 DataFrame 分成四個相等的部分。但是,嘗試使用 np.split(df, 4) 會拋出「ValueError:陣列分割不會導致均分」錯誤。

要解決此問題,應使用 np.array_split。與np.split不同,np.array_split允許indices_or_sections是一個不產生等軸分割的整數。

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

# Create a DataFrame
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)})

# Split the DataFrame into three equal parts
result = np.array_split(df, 3)

# Print the results
for i in range(len(result)):
    print(f"Part {i + 1}:")
    print(result[i])
    print()</code>

此程式碼將把DataFrame分成三個近似相等的部分。零件數量可依需求調整。

以上是如何將大型 Pandas DataFrame 分成相等的部分?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn