title: I'm iterating a dataframe with a for loop, does anybody know a faster way of doing this?
body: <p>I'm working on a dataframe where I need to add a new column which is based on other existing rows in the dataframe. Here is a simplified version of what I'm trying to do. Basically there is a dataframe with the purchase and sale record of a particular stock:</p>
  <pre><code>data = {'Name' :['Al', 'John', 'Jack', 'Jack', 'Al', 'John', 'Jack', 'Jack'],
  'TradeType' : ['Purch', 'Sold', 'Sold', 'Purch', 'Sold', 'Sold', 'Purch', 'Sold'],
  'Date' : [ 2019, 2020, 2021, 2022, 2019, 2020, 2021, 2022]}
  
  df = pd.DataFrame(data)
  </code></pre>
  <p>I want to add a new column called 'nTrans2Year' that tells me how many transaction that person has done in the previous two years. The way I am currently doing it is such: I create e temporary dataframe with the right filters and than calculate its length.</p>
  <pre><code>df['nTrans2Year'] = 0
  df = df.reset_index(drop=True)
  for index, row in df.iterrows():
    insName = row['Name']
    date = row['Date']
    tradeType = row['TradeType']
    t_df = df[(df['Name'] == insName) &amp; (df['TradeType'] == tradeType) &amp; (df['Date'] &lt; date) &amp; (df['Date'] &gt; (date - dt.timedelta(days = 365*2)))]
    df.loc[index ,'nTrans2Year'] = len(t_df)
  </code></pre>
  <p>The only issue with this approach is that it is very computationally intensive, and given that my original dataframe is 300k rows long it's not really an option. Does anybody have a more efficient way of achieving the same result?</p>