擅长:python、mysql、java
<p>我建议您将合并列设置为索引,并使用<code>df1.join(df2)</code>而不是<code>merge</code>,这样会更快。</p>
<p>以下是一些示例,包括分析:</p>
<pre><code>In [1]:
import pandas as pd
import numpy as np
df1 = pd.DataFrame(np.arange(1000000), columns=['A'])
df1['B'] = np.random.randint(0,1000,(1000000))
df2 = pd.DataFrame(np.arange(1000000), columns=['A2'])
df2['B2'] = np.random.randint(0,1000,(1000000))
</code></pre>
<p>这是a和A2上的常规左合并:</p>
<pre><code>In [2]: %%timeit
x = df1.merge(df2, how='left', left_on='A', right_on='A2')
1 loop, best of 3: 441 ms per loop
</code></pre>
<p>同样,使用join:</p>
<pre><code>In [3]: %%timeit
x = df1.set_index('A').join(df2.set_index('A2'), how='left')
1 loop, best of 3: 184 ms per loop
</code></pre>
<p>现在很明显,如果您可以在循环之前设置索引,那么在时间方面的收益将大得多:</p>
<pre><code># Do this before looping
In [4]: %%time
df1.set_index('A', inplace=True)
df2.set_index('A2', inplace=True)
CPU times: user 9.78 ms, sys: 9.31 ms, total: 19.1 ms
Wall time: 16.8 ms
</code></pre>
<p>然后在循环中,您将得到在本例中速度是30倍的结果:</p>
<pre><code>In [5]: %%timeit
x = df1.join(df2, how='left')
100 loops, best of 3: 14.3 ms per loop
</code></pre>