gpt4 book ai didi

python - 跨行执行聚合函数(例如平均值)会产生 NaN

转载 作者:行者123 更新时间:2023-12-01 06:25:21 24 4
gpt4 key购买 nike

我正在使用爱荷华州艾姆斯的住房定价数据集,并遇到了一个我认为很简单的问题。

我根据年和月平均价格的数据透视表创建了一个数据框。我正在尝试计算平均每月价格。

当我这样做时,我得到 NaN 而不是 float 。

df_viz = pd.DataFrame(pd.pivot_table(df,index=['MoSold'], columns=['YrSold'],values=['SalePrice'],aggfunc='mean').to_records())
df_viz = df_viz.set_index(['MoSold'])
df_viz.columns = [hdr.replace("(", "").replace(")", "").replace("'","").replace(", ","") \
for hdr in df_viz.columns]
df_viz['mean_monthly_saleprice']=df_viz.mean(axis=0)
df_viz

什么给了?我该如何解决这个问题?

谢谢。

enter image description here

最佳答案

您可能指定了错误的轴。尝试:

df_viz['mean_monthly_saleprice']=df_viz.mean(axis=1)
<小时/>

至于为什么您的原始代码返回 na,df_viz.mean(axis=0) 按列生成平均值。结果是一个以列名作为标签的系列:

SalePrice2006    <a number>
SalePrice2007 <a number>
SalePrice2008 <a number>
SalePrice2009 <a number>
SalePrice2010 <a number>

然后,您尝试将该系列与标记为 MoSolddf_viz 数据框结合起来。两个索引之间没有匹配的标签。因此你的结果是 na。

故事的寓意:索引在数据框中非常重要。好好注意他们。

关于python - 跨行执行聚合函数(例如平均值)会产生 NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60179036/

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