title: How to compare current row with previous 2 rows based on certain conditions in Python
body: <p>I have a dataset similar to below, I want to compare all rows for each inventory item based on the conditions that</p>
  <ol>
  <li><p>if &quot;value&quot; column is not null, then flag it &quot;yes&quot;</p>
  </li>
  <li><p>Else if &quot;value&quot; column for all row (per each inventory) is null, then evaluate the &quot;item&quot; column, if either &quot;item&quot; column is not null, then that row should be flagged &quot;yes&quot;. Or 1 record under &quot;value&quot; is null where 2 records under &quot;value&quot; is not null, then those 2 rows need to be evaluated based on the item</p>
  </li>
  <li><p>In the case that if both &quot;value&quot; and &quot;item&quot; are both null(per each inventory), evaluate the &quot;year&quot; column and flag the most updated year &quot;yes&quot;. Or &quot;value&quot; is null but 1 record under &quot;item&quot; is null where 2 records under &quot;item&quot; is not null, then evaluate the &quot;year&quot; column and flag the most updated year &quot;yes&quot;</p>
  </li>
  <li><p>df['flag'].fillna('no',inplace=True)</p>
  </li>
  </ol>
  <p>I can set up this if then else logic but I don't know how to compare current row with 2 previous rows. The groupby with transform and custom function are great advices and I wonder how to capture all these scenarios or if there is a better way.</p>
  <p>Below is how the simplified df would look like. In my real dataset, as described above, there are also cases that for the same inventory, &quot;value&quot; column are all null, but there are 2 rows under &quot;item&quot; are not null, in that case, &quot;year&quot; column needs to be evaluated for those 2 rows.</p>
  <pre><code>df1 = { 'inventory':['inv1','inv1','inv1','inv2','inv2','inv2','inv3','inv3','inv3'],
    'value':['xyz','','','','','','','',''],
    'item':['','304','304','','205','','','',''],
     'year':[2020,2020,2020,2020,2020,2020,2019,2018,2020]}
  
  df1=pd.DataFrame(df1)
  </code></pre>
  <p>desired output would be like below - adding a flag column to flag 'yes'/'no' based on the above multiple condtions.</p>
  <p><a href="https://i.stack.imgur.com/5Bb0Q.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5Bb0Q.png" alt="enter image description here" /></a></p>