我有一个大型数据框(>3MM 行),我试图通过一个函数传递该数据框(下面的函数在很大程度上简化了),并且我不断收到一条
Memory Error
消息。
我认为我将太大的数据帧传递到函数中,所以我尝试:
1)将数据帧切成更小的块(最好按
AcctName
切片)
2)将数据帧传递到函数中
3)将数据帧连接回一个大数据帧
def trans_times_2(df):
df['Double_Transaction'] = df['Transaction'] * 2
large_df
AcctName Timestamp Transaction
ABC 12/1 12.12
ABC 12/2 20.89
ABC 12/3 51.93
DEF 12/2 13.12
DEF 12/8 9.93
DEF 12/9 92.09
GHI 12/1 14.33
GHI 12/6 21.99
GHI 12/12 98.81
我知道我的函数可以正常工作,因为它可以在较小的数据帧(例如 40,000 行)上工作。我尝试了以下操作,但未能成功将小数据帧连接回一个大数据帧。
def split_df(df):
new_df = []
AcctNames = df.AcctName.unique()
DataFrameDict = {elem: pd.DataFrame for elem in AcctNames}
key_list = [k for k in DataFrameDict.keys()]
new_df = []
for key in DataFrameDict.keys():
DataFrameDict[key] = df[:][df.AcctNames == key]
trans_times_2(DataFrameDict[key])
rejoined_df = pd.concat(new_df)
我如何设想数据帧被分割:
df1
AcctName Timestamp Transaction Double_Transaction
ABC 12/1 12.12 24.24
ABC 12/2 20.89 41.78
ABC 12/3 51.93 103.86
df2
AcctName Timestamp Transaction Double_Transaction
DEF 12/2 13.12 26.24
DEF 12/8 9.93 19.86
DEF 12/9 92.09 184.18
df3
AcctName Timestamp Transaction Double_Transaction
GHI 12/1 14.33 28.66
GHI 12/6 21.99 43.98
GHI 12/12 98.81 197.62
您可以使用列表理解将数据帧拆分为列表中包含的更小的数据帧。
n = 200000 #chunk row size
list_df = [df[i:i+n] for i in range(0,df.shape[0],n)]
或者使用 numpy
array_split
,请参阅此评论以了解差异:
list_df = np.array_split(df, n)
您可以通过以下方式访问块:
list_df[0]
list_df[1]
etc...
然后您可以使用 pd.concat 将其组装回一个数据帧。
按账户名称
list_df = []
for n,g in df.groupby('AcctName'):
list_df.append(g)
more_itertools
。它处理所有边缘情况,例如数据帧的不均匀分区,并返回一个迭代器,这将使事情变得更加高效。
(使用@Acumenus 的代码更新)
from more_itertools import sliced
CHUNK_SIZE = 5
index_slices = sliced(range(len(df)), CHUNK_SIZE)
for index_slice in index_slices:
chunk = df.iloc[index_slice] # your dataframe chunk ready for use
我喜欢@ScottBoston 的回答,尽管我仍然没有记住咒语。这是一个更详细的函数,可以做同样的事情:
def chunkify(df: pd.DataFrame, chunk_size: int):
start = 0
length = df.shape[0]
# If DF is smaller than the chunk, return the DF
if length <= chunk_size:
yield df[:]
return
# Yield individual chunks
while start + chunk_size <= length:
yield df[start:chunk_size + start]
start = start + chunk_size
# Yield the remainder chunk, if needed
if start < length:
yield df[start:]
要重建数据框,请将每个块累积到列表中,然后
pd.concat(chunks, axis=1)
感谢您的解决方案。
我尝试了两种建议的方法:
方法一:
n = 10**6
list_df = [df[i:i+n] for i in range(0, df.shape[0], n)]
list_df[0]
这样更快。
方法二:
import numpy as np
import math
n = 10**6
list_df = np.array_split(df, math.ceil(len(df)/n))
list_df[0]
这比较慢。