【发布时间】:2014-09-22 16:25:54
【问题描述】:
尝试使用 pandas 合并两个数据帧时,我收到以下消息:“ValueError:数组太大。”我估计合并后的表将有大约 50 亿行,这对于我的 8GB RAM 的计算机来说可能太多了(这仅受我的 RAM 限制还是它内置在 pandas 系统中?)。
我知道,一旦我有了合并表,我将计算一个新列,然后过滤行,寻找组内的最大值。因此最终的输出表将只有 250 万行。
我怎样才能打破这个问题,以便我可以在较小的部分上执行这个合并方法并建立输出表,而不会达到我的 RAM 限制?
下面的方法适用于这个小数据,但在更大的真实数据上失败:
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()]
这是对前两个问题的后续:
Does iterrows have performance issues?
What is a good way to avoid using iterrows in this example?
我在下面回答我自己的问题。
【问题讨论】: