拆分大熊猫数据框

问题描述 投票:0回答:10

我有一个包含 423244 行的大型数据框。我想把它分成 4 个。我尝试了以下代码,但出现错误?

ValueError: array split does not result in an equal division

for item in np.split(df, 4):
    print item

如何将此数据框分成 4 组?

python pandas
10个回答
345
投票

使用

np.array_split

Docstring:
Split an array into multiple sub-arrays.

Please refer to the ``split`` documentation.  The only difference
between these functions is that ``array_split`` allows
`indices_or_sections` to be an integer that does *not* equally
divide the axis.
In [1]: import pandas as pd

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

In [3]: print df
     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

In [4]: import numpy as np
In [5]: np.array_split(df, 3)
Out[5]: 
[     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,
      A      B         C         D
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
6  foo    one  0.131529 -0.968151
7  foo  three -1.002946 -0.257468]

84
投票

我想做同样的事情,我首先遇到了 split 函数的问题,然后安装 pandas 0.15.2 出现了问题,所以我回到了旧版本,编写了一个运行良好的小函数。我希望这能有所帮助!

# input - df: a Dataframe, chunkSize: the chunk size
# output - a list of DataFrame
# purpose - splits the DataFrame into smaller chunks
def split_dataframe(df, chunk_size = 10000): 
    chunks = list()
    num_chunks = len(df) // chunk_size + 1
    for i in range(num_chunks):
        chunks.append(df[i*chunk_size:(i+1)*chunk_size])
    return chunks

49
投票

请注意,

np.array_split(df, 3)
将数据帧分割成3个子数据帧,而
@elixir的答案
中定义的split_dataframe函数,当被称为
split_dataframe(df, chunk_size=3)
时,每
chunk_size
行分割数据帧。

示例:

np.array_split

df = pd.DataFrame([1,2,3,4,5,6,7,8,9,10,11], columns=['TEST'])
df_split = np.array_split(df, 3)

...您将获得 3 个子数据框:

df_split[0] # 1, 2, 3, 4
df_split[1] # 5, 6, 7, 8
df_split[2] # 9, 10, 11

split_dataframe

df_split2 = split_dataframe(df, chunk_size=3)

...您将获得 4 个子数据框:

df_split2[0] # 1, 2, 3
df_split2[1] # 4, 5, 6
df_split2[2] # 7, 8, 9
df_split2[3] # 10, 11

希望我是对的,并且这很有用。


34
投票

我想现在我们可以使用普通的

iloc
range
来实现这一点。

chunk_size = int(df.shape[0] / 4)
for start in range(0, df.shape[0], chunk_size):
    df_subset = df.iloc[start:start + chunk_size]
    process_data(df_subset)
    ....

11
投票

您可以使用列表推导式在一行中完成此操作

n = 4
chunks = [df[i:i+n] for i in range(0,df.shape[0],n)]

8
投票

注意:

np.array_split
不适用于 numpy-1.9.0。我查了一下:它适用于 1.8.1。

错误:

Dataframe 没有“大小”属性


7
投票

我喜欢俏皮话,所以@LucyDrops 的答案对我有用。

但是,有一件重要的事情:如果块应该是原始

.copy()
部分的副本,请添加一个
df

chunks = [df[i:i+n].copy() for i in range(0,df.shape[0],n)]

否则在进一步处理

chunks
时(例如循环中)很有可能收到下一个警告:

A value is trying to be set on a copy of a slice from a DataFrame.

(详情请参阅Pandas文档


7
投票

基于@elixir 的回答...
我建议使用发电机 避免加载内存中的所有块:

def chunkit(df, chunk_size = 10000): 
    num_chunks = len(df) // chunk_size
    if len(df) % chunk_size != 0 or len(df) == 0:
        num_chunks += 1
    for i in range(num_chunks):
        yield df[i*chunk_size:(i + 1) * chunk_size]

5
投票

您可以使用

groupby
,假设您有一个整数枚举索引:

import math
df = pd.DataFrame(dict(sample=np.arange(99)))
rows_per_subframe = math.ceil(len(df) / 4.)

subframes = [i[1] for i in df.groupby(np.arange(len(df))//rows_per_subframe)]

注意:

groupby
返回一个元组,其中第二个元素是数据帧,因此提取稍微复杂。

>>> len(subframes), [len(i) for i in subframes]
(4, [25, 25, 25, 24])

1
投票

我也经历过

np.array_split
无法使用Pandas DataFrame。我的解决方案是仅拆分 DataFrame 的索引,然后引入带有“group”标签的新列:

indexes = np.array_split(df.index,N, axis=0)
for i,index in enumerate(indexes):
   df.loc[index,'group'] = i

这使得groupby操作非常方便,比如计算每组的平均值:

df.groupby(by='group').mean()
© www.soinside.com 2019 - 2024. All rights reserved.