【发布时间】:2014-09-12 07:17:48
【问题描述】:
我注意到使用 pandas 的 iterrows 时性能很差。
这是别人经历过的事情吗?它是特定于 iterrows 的吗?对于特定大小的数据(我正在处理 2-3 百万行),是否应该避免使用此函数?
This discussion GitHub 上的 This discussion 让我相信这是在数据框中混合 dtype 时引起的,但是下面的简单示例显示即使使用一种 dtype (float64) 也存在这种情况。这在我的机器上需要 36 秒:
import pandas as pd
import numpy as np
import time
s1 = np.random.randn(2000000)
s2 = np.random.randn(2000000)
dfa = pd.DataFrame({'s1': s1, 's2': s2})
start = time.time()
i=0
for rowindex, row in dfa.iterrows():
i+=1
end = time.time()
print end - start
为什么像 apply 这样的矢量化操作会这么快?我想那里也必须进行一些逐行迭代。
在我的情况下,我无法弄清楚如何不使用 iterrows(我会留到以后的问题)。因此,如果您一直能够避免这种迭代,我将不胜感激。我正在根据单独数据框中的数据进行计算。谢谢!
---编辑:下面添加了我要运行的简化版本---
import pandas as pd
import numpy as np
#%% Create the original tables
t1 = {'letter':['a','b'],
'number1':[50,-10]}
t2 = {'letter':['a','a','b','b'],
'number2':[0.2,0.5,0.1,0.4]}
table1 = pd.DataFrame(t1)
table2 = pd.DataFrame(t2)
#%% Create the body of the new table
table3 = pd.DataFrame(np.nan, columns=['letter','number2'], index=[0])
#%% Iterate through filtering relevant data, optimizing, returning info
for row_index, row in table1.iterrows():
t2info = table2[table2.letter == row['letter']].reset_index()
table3.ix[row_index,] = optimize(t2info,row['number1'])
#%% Define optimization
def optimize(t2info, t1info):
calculation = []
for index, r in t2info.iterrows():
calculation.append(r['number2']*t1info)
maxrow = calculation.index(max(calculation))
return t2info.ix[maxrow]
【问题讨论】:
-
apply未矢量化。iterrows更糟糕,因为它将所有东西都装箱了(这就是与apply的性能差异)。你应该只在极少数情况下使用iterrows。恕我直言,从来没有。使用iterrows显示您实际在做什么。 -
您链接到的问题与将
DatetimeIndex装箱到Timestamps(在python 空间中实现)有关,这在master 中得到了很大改进。 -
查看此问题以获得更完整的讨论:github.com/pydata/pandas/issues/7194。
-
链接到具体问题(这个问题将保持一般性):stackoverflow.com/questions/24875096/…
-
Please do not recommend the use of iterrows(). 这是 pandas 历史上最糟糕的反模式的公然推动者。
标签: python performance pandas iteration