Arpan Ghimire
Arpan Ghimire

Reputation: 383

Replace Nan with previous row value in pandas dataframe

I have a dataframe named purchase_df with columns (purchase_item, purchase_date, purchase_quantity, purchase_price_unit, sales_quantity) and some of the value of purchase_price_unit is Nan(empty) and I need to replace Nan value with previous month value

Note:- I saw this one (Python pandas, replace a NAN on a column with previous value on the same column) but here they haven't used group by which is major problem in this task.

For this I tried doing this

# grouped = purchase_df.groupby('purchase_item')
grouped = purchase_df.groupby(['purchase_item','purchase_date'])
purchase_df['purchase_price_unit'] = grouped['purchase_price_unit'].apply(lambda x: x.ffill())

Here I group the data by purchase_item and purchase_date and used ffill() which fill value of previous rows but it didn't work even though this method replace nan with previous rows if I group by just using purchase_item but here I need to group by according to purchase_item as well as purchase_date. Help me out

Upvotes: 1

Views: 243

Answers (1)

ali bakhtiari
ali bakhtiari

Reputation: 1097

Apply the function within your groupby objects:

purchase_df.groupby(['purchase_item','purchase_date']).apply(lambda x: x.ffill())

Upvotes: 0

Related Questions