gpt4 book ai didi

python - 根据组填充Nan

转载 作者:行者123 更新时间:2023-12-01 02:56:38 26 4
gpt4 key购买 nike

我想根据列值的平均值填充 NaN。示例:

       Groups      Temp

1 5 27
2 5 23
3 5 NaN (will be replaced by 25)
4 1 NaN (will be replaced by the mean of the Temps that are in group 1)

有什么建议吗?谢谢!

最佳答案

groupbytransfrom和lamdba函数与fillnamean结合使用:

df = df.assign(Temp=df.groupby('Groups')['Temp'].transform(lambda x: x.fillna(x.mean())))
print(df)

输出:

   Temp
0 27.0
1 23.0
2 25.0
3 NaN

关于python - 根据组填充Nan,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44166551/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com