[英]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我有一个名为purchase_df
的 dataframe,其中包含列( purchase_item
、 purchase_date
、 purchase_quantity
、 purchase_price_unit
、 sales_quantity
)并且purchase_price_unit
的某些值是Nan (空),我需要用上个月的值替换Nan值
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.注意:- 我看到了这个( Python pandas,将一列上的 NAN 替换为同一列上的先前值)但这里他们没有使用 group by 这是此任务中的主要问题。
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
.在这里,我按purchase_item
和purchase_date
对数据进行分组,并使用ffill()
来填充前几行的值,但是如果我仅使用purchase_item
进行分组,即使此方法将nan替换为前几行,它也不起作用,但在这里我需要根据到purchase_item
和purchase_date
。 Help me out帮帮我
Apply the function within your groupby objects:在 groupby 对象中应用 function:
purchase_df.groupby(['purchase_item','purchase_date']).apply(lambda x: x.ffill())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.