熊猫数据框获得两个类别的平均值并放入现有列(Pandas dataframe getting average of two categories and placing in to existing

编程入门 行业动态 更新时间:2024-10-07 08:20:39
熊猫数据框获得两个类别的平均值并放入现有列(Pandas dataframe getting average of two categories and placing in to existing column)

我有一个按日期(许多相同的日期)索引的日期框架df。 我也有一个名为name的列,每个日期都有公司名称,评级(A到Z)和类别(健康,公用事业)等,最后是一个名为price的列。

价格由许多空白值和一些填充值组成,我想填充空白以其他价格的平均价格,这些价格在具有相同评级和相同类别的公司的列价格中需要填写。

I have a dateframe df which is indexed by date (many same dates). I also have a column named name which has company names for each date, rating (A to Z) and category (health, utilities) etc and finally a column called price.

Price consists of many blank values with some populated values I want to fill the blanks with the average price of the other prices which are in the column price for the companies with the same rating and same category of the one which needs to be filled.

最满意答案

尝试这个

dt['adjPrice'] = dt.groupby(['rating', 'category']).price.apply(lambda s: s.fillna(s.mean()))

Try this

dt['adjPrice'] = dt.groupby(['rating', 'category']).price.apply(lambda s: s.fillna(s.mean()))

更多推荐

本文发布于:2023-08-07 13:17:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1464132.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:熊猫   平均值   放入   类别   两个

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!