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
Apply the function within your groupby objects:
purchase_df.groupby(['purchase_item','purchase_date']).apply(lambda x: x.ffill())
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.