我正在与爱荷华州埃姆斯市的一个住房价格数据集合作,遇到了我认为很简单的问题。
我从按年和月平均价格的数据透视表中创建了一个数据框。我正在尝试计算平均每月价格。
当我这样做时,我得到的是NaN而不是浮点数。
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
什么给了?我该如何解决?
谢谢。
您可能指定了错误的轴。试试:
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>
然后您尝试将该系列与df_viz
数据帧组合在一起,该数据帧由MoSold
标记。两个索引之间没有匹配的标签。因此,您的结果是不。
故事的道德:索引在数据框中非常重要。请注意它们。