Optimizing for loop in python
<p>I have a dataframe (df) with distance traveled and I have assigned a label based on certain conditions.</p>

<pre><code>distance=[0,0.0001,0.20,1.23,4.0]
df = pd.DataFrame(distance,columns=["distance"])
df['label']=0
for i in range(0, len(df['distance'])):   
      if (df['distance'].values[i])&lt;=0.10:
          df['label'][i]=1
      elif (df['distance'].values[i])&lt;=0.50:
          df['label'][i]=2
      elif (df['distance'].values[i])&gt;0.50:
          df['label'][i]=3
</code></pre>

<p>This is working fine. However, I have more than 1 million records with distance and this for loop is taking longer time than expected. Can we optimize this code to reduce the execution time?</p>

<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.cut.html" rel="nofollow"><code>cut</code></a> by assigning labels to the bins:</p>

<pre><code>pd.cut(df.distance, [-np.inf, 0.1, 0.5, np.inf], labels=[1,2,3])

0    1
1    1
2    2
3    3
4    3
</code></pre>

python pandas for-loop optimization