How to sum values of a row of a pandas dataframe efficiently
<p>I have a <code>python dataframe</code> with 1.5 million rows and 8 columns. I want combine few columns and create a new column. I know how to do this but wanted to know which one is faster and efficient. I am reproducing my code here </p>

<pre><code>import pandas as pd
import numpy as np
df=pd.Dataframe(columns=['A','B','C'],data=[[1,2,3],[4,5,6],[7,8,9]])
</code></pre>

<p>Now here is what I want to achieve </p>

<pre><code>df['D']=0.5*df['A']+0.3*df['B']+0.2*df['C']
</code></pre>

<p>The other alternative is to use the <code>apply functionality</code> of pandas</p>

<pre><code>df['D']=df.apply(lambda row: 0.5*row['A']+0.3*row['B']+0.2*row['C'])
</code></pre>

<p>I wanted to know which method takes less time when we have 1.5 millon rows and have to combine 8 columns</p>

<p>First method is faster, because is vectorized:</p>

<pre><code>df=pd.DataFrame(columns=['A','B','C'],data=[[1,2,3],[4,5,6],[7,8,9]])
print (df)

#[30000 rows x 3 columns]
df = pd.concat([df]*10000).reset_index(drop=True)

df['D1']=0.5*df['A']+0.3*df['B']+0.2*df['C']
#similar timings with mul function
#df['D1']=df['A'].mul(0.5)+df['B'].mul(0.3)+df['C'].mul(0.2)

df['D']=df.apply(lambda row: 0.5*row['A']+0.3*row['B']+0.2*row['C'], axis=1)

print (df)

In [54]: %timeit df['D2']=df['A'].mul(0.5)+df['B'].mul(0.3)+df['C'].mul(0.2)
The slowest run took 10.84 times longer than the fastest. This could mean that an intermediate result is being cached.
1000 loops, best of 3: 950 Âµs per loop

In [55]: %timeit df['D1']=0.5*df['A']+0.3*df['B']+0.2*df['C']
The slowest run took 4.76 times longer than the fastest. This could mean that an intermediate result is being cached.
1000 loops, best of 3: 1.2 ms per loop

In [56]: %timeit df['D']=df.apply(lambda row: 0.5*row['A']+0.3*row['B']+0.2*row['C'], axis=1)
1 loop, best of 3: 928 ms per loop
</code></pre>

<p>Another testing in <code>1.5M</code> size <code>DataFrame</code>, <code>apply</code> method is very slow:</p>

<pre><code>#[1500000 rows x 6 columns]
df = pd.concat([df]*500000).reset_index(drop=True)

In [62]: %timeit df['D2']=df['A'].mul(0.5)+df['B'].mul(0.3)+df['C'].mul(0.2)
10 loops, best of 3: 34.8 ms per loop

In [63]: %timeit df['D1']=0.5*df['A']+0.3*df['B']+0.2*df['C']
10 loops, best of 3: 31.5 ms per loop

In [64]: %timeit df['D']=df.apply(lambda row: 0.5*row['A']+0.3*row['B']+0.2*row['C'], axis=1)
1 loop, best of 3: 47.3 s per loop
</code></pre>

python performance pandas numpy vectorization