title: How can this for loop be written to process faster in Python?
body: <p>I'm not familiar enough with Python to understand how I can make a for loop go faster. Here's what I'm trying to do.</p>
  <p>Let's say we have the following dataframe of prices.</p>
  <pre><code>import pandas as pd
  
  df = pd.DataFrame.from_dict({'price': {0: 98, 1: 99, 2: 101, 3: 99, 4: 97, 5: 100, 6: 100, 7: 98}})
  </code></pre>
  <p>The goal is to create a new column called updown, which classifies each row as &quot;up&quot; or &quot;down&quot;, signifying what comes first when looking at each subsequent row - up by 2, or down by 2.</p>
  <pre><code>df['updown'] = 0
  for i in range(df.shape[0]):
      j=0
      while df.price.iloc[i+j] &lt; (df.price.iloc[i] + 2) and df.price.iloc[i+j] &gt; (df.price.iloc[i] - 2):
          j= j+1
      if df.price.iloc[i+j] &gt;= (df.price.iloc[i] + 2):
          df.updown.iloc[i] = &quot;Up&quot;
      if df.price.iloc[i+j] &lt;= (df.price.iloc[i] - 2):
          df.updown.iloc[i] = &quot;Down&quot;
  </code></pre>
  <p>This works just fine, but simply runs too slow when running on millions of rows. Note that I am aware the code throws an error once it gets to the last row, which is fine with me.</p>
  <p>Where can I learn how to make something like this happen much faster (ideally seconds, or at least minutes, as opposed to 10+ hours, which is how long it takes right now.</p>