title: How to fill last non-null value for each user in pandas?
body: <p>I have a df with user journeys that show purchase amounts of products. Now, I want to fill the last non-null value for each user, since users do not buy every day. currently, I have:</p>
  <pre><code>date       | user_id | purchase_value
  2020-01-01 | 1       | null
  2020-01-02 | 1       | 1
  2020-01-03 | 1       | null
  2020-01-04 | 1       | 4
  2020-01-01 | 2       | 55
  2020-01-02 | 2       | null
  </code></pre>
  <p>I want it to look like this:</p>
  <pre><code>date       | user_id | purchase_value
  2020-01-01 | 1       | null
  2020-01-02 | 1       | 1
  2020-01-03 | 1       | 1
  2020-01-04 | 1       | 4
  2020-01-01 | 2       | 55
  2020-01-02 | 2       | 55
  </code></pre>
  <p>Explanation: For user 1, we fill 1 on 2020-01-03 since this was the last non-null value on 2020-01-02. For user 2, we fill in 55 on 2020-01-02  since this was the last non-null value on 2020-01-01.</p>
  <p>How would I do this in pandas for each user_id and date? Also, the dates do not have to be sequential. i.e. there can be gaps in the dates, in that case always fill in the last non-null value (whenever that was).</p>
  <p>Update:
  I tried using this solution but the fill-forward does not occur as expected. It does take the next (future) date instead of the last non-null value. See img</p>
  <pre><code>df.groupby(['user_id'], sort=True)['purchase_amount'].apply(lambda x: x.ffill())
  </code></pre>
  <p>The first column is the actual normalized purchase amount for user=1 and the next column is the result from the formula. The first Nan should be replaced with 0.72, not 0.06.</p>
  <p><a href="https://i.stack.imgur.com/5Yxq7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5Yxq7.png" alt="enter image description here" /></a></p>