-4
Year    Price
2010     60.000
2010     70.000 
2010     nan    
2009     92.000     
2008     160.000  
2008     nan  
2008     87.000

I want to replace the nan values with the average prices of the years they belong to. I want my output something like this:

    Year    Price
    2010     60.000
    2010     70.000 
    2010     65.000    
    2009     92.000     
    2008     160.000  
    2008     123.500  
    2008     87.000

How can I get it?

  • To get good answers to your question, please share the piece of code you tried and meet the minimum repeatability principle. To learn how to ask questions, read this article: [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) – Sercan Jan 04 '22 at 09:43
  • 1
    Does this answer your question? [How to replace NaN values by Zeroes in a column of a Pandas Dataframe?](https://stackoverflow.com/questions/13295735/how-to-replace-nan-values-by-zeroes-in-a-column-of-a-pandas-dataframe) – Sercan Jan 04 '22 at 09:45
  • To learn about minimum repeatability on SO, you can read this article: [How to create a Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) – Sercan Jan 04 '22 at 09:51

1 Answers1

-1

You can try like:

df["Price"] = df.groupby("Year").transform(lambda x: x.fillna(x.mean()))

enter image description here Reference Pandas: filling missing values by mean in each group

kingkong
  • 122
  • 6
  • FYI: not my downvote but you're answering an already answered question as you link maybe thats the reason for it. –  Jan 03 '22 at 12:34
  • @Neither Ok, my mistake, but I don't have 50 reputation to put links in comments :( – kingkong Jan 03 '22 at 12:37