Pandas:合并数组太大,如何分部分合并?

3 投票
1 回答
2688 浏览
提问于 2025-04-18 15:24

在用pandas合并两个数据表时,我收到了这个提示:“ValueError: array is too big.” 我估计合并后的表大约会有50亿行,这对我只有8GB内存的电脑来说可能太多了(这是因为我的内存限制,还是pandas系统本身的限制?)。

我知道一旦合并完成,我会计算一个新列,然后过滤出行,寻找每组中的最大值。因此,最终的输出表只会有250万行。

我该如何将这个问题拆分开,以便在较小的部分上执行合并,而不触及我的内存限制呢?

下面的方法在处理小数据时是有效的,但在处理更大的真实数据时就失败了:

import pandas as pd
import numpy as np

# Create input tables
t1 = {'scenario':[0,0,1,1],
      'letter':['a','b']*2,
      'number1':[10,50,20,30]}

t2 = {'letter':['a','a','b','b'],
      'number2':[2,5,4,7]}

table1 = pd.DataFrame(t1)
table2 = pd.DataFrame(t2)

# Merge the two, create the new column. This causes "...array is too big."
table3 = pd.merge(table1,table2,on='letter')
table3['calc'] = table3['number1']*table3['number2']

# Filter, bringing back the rows where 'calc' is maximum per scenario+letter
table3 = table3.loc[table3.groupby(['scenario','letter'])['calc'].idxmax()]

这是对之前两个问题的后续:

iterrows有性能问题吗?

在这个例子中,有什么好的方法可以避免使用iterrows?

我在下面回答了我自己的问题。

1 个回答

0

你可以通过按某个条件(比如'scenario')把第一个表格分组。首先,创建一个新的变量,这个变量可以把数据分成你想要的大小的组。然后,你可以遍历这些组,对每一组做以下操作:执行一个新的合并,过滤数据,然后把处理好的小数据添加到最终的输出表格中。

正如在“iterrows有性能问题吗?”中提到的,遍历数据是比较慢的。因此,尽量使用大组,这样可以让处理更高效。Pandas在合并数据时相对较快

在你创建输入表格之后继续进行

table3 = pd.DataFrame()

grouped = table1.groupby('scenario')

for _, group in grouped: 
    temp = pd.merge(group,table2, on='letter')
    temp['calc']=temp['number1']*temp['number2']
    table3 = table3.append(temp.loc[temp.groupby('letter')['calc'].idxmax()])
    del temp

撰写回答