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>Comes with a warning about setting a value on a copy of a slice, but maybe someone can suggest a cleaner alternative? </p>

<p>Just based on fancy indexing to get the sub-array based on distance and then writing the values you want to it.</p>

<pre><code>df.loc[:, "label"][df.loc[:, "distance"] &lt;= 0.1] = 1
df.loc[:, "label"][(0.1 &lt; df.loc[:, "distance"]) &amp; (df.loc[:, "distance"] &lt;= 0.5)] = 2
df.loc[:, "label"][df.loc[:, "distance"] &gt; 0.5] = 3
</code></pre>

<p>EDIT: New and improved, without chained indexing.</p>

python pandas for-loop optimization