我有一个包含 423244 行的大型数据框。我想将其拆分为 4。我尝试了以下给出错误的代码?ValueError: array split does not result in an equal division
for item in np.split(df, 4):
print item
如何将此数据框分成 4 组?
使用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]
我也想做同样的事情,我首先遇到了 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
我想现在我们可以为此使用 plain iloc
with 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)
....
请注意,np.array_split(df, 3)
将数据帧拆分为 3 个子数据帧,而在@elixir 的答案split_dataframe
中定义的函数在调用 as 时,会每行拆分数据帧。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
希望我是对的,这很有用。
警告:
np.array_split
不适用于 numpy-1.9.0。我签出:它适用于 1.8.1。
错误:
数据框没有“大小”属性
您可以使用列表推导在一行中执行此操作
n = 4
chunks = [df[i:i+n] for i in range(0,df.shape[0],n)]
您可以使用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])
以@elixir 的回答为基础...
我建议使用生成器来避免将所有块加载到内存中:
def chunkit(df, chunk_size = 10000):
num_chunks = len(df) // chunk_size
if len(df) % chunk_size != 0:
num_chunks += 1
for i in range(num_chunks):
yield df[i*chunk_size:(i + 1) * chunk_size]
我喜欢单线,所以@LucyDrops 回答对我有用。
但是,有一件重要的事情:添加一个.copy()
if 块应该是原始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 文档中的详细信息)
我也经历过np.array_split
不使用 Pandas DataFrame。我的解决方案是只拆分 DataFrame 的索引,然后引入一个带有“组”标签的新列:
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()