Python Dataframe - 计算组的平均值并存储

标签 python dataframe

我正在用Python编码。数据框full_df具有以下特征:building_idlog_price。我想计算按 building_id 分组的 log_price 的平均值以及创建的 full_df 中的新特征 mean_log_price,存储根据 building_id 得出的 log_price 平均值。

我有以下代码:

    full_df['mean_log_price'] = full_df.groupby(['building_id'],as_index=False).agg(np.mean)['log_price']

但是,当我查看 full_df 时,mean_log_price 的某些值是 NaN,并且在我进行一些检查后,某些值不正确。为什么会发生这种情况以及有哪些替代方法?提前致谢。

最佳答案

agg 将更改结果的长度并破坏索引,因此通过将较小的对象分配给较大的数据帧将无法获得正确的结果。这里您需要 transform,它保留 Series 的长度和索引,以便可以将其分配回数据框:

full_df['mean_log_price'] = full_df.groupby('building_id')['log_price'].transform('mean')

关于Python Dataframe - 计算组的平均值并存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42917173/

相关文章:

python - pandas merge df many to many without duplicates

Python 思维波图

python - 按升序对目录中的文件名进行排序

python - Grumpy 生成的 helloworld.go 的二进制文件没有生成

python - 如果值列表出现在 Pandas 数据框的任何列中,如何打印行

在 R 中重新排序字母数字年龄组

python - 请求的模块不可用 : vtkRenderingOpenGL-cmake/OpenCVDetectVTK. cmake:6 (find_package)

python - 是否可以从代码进入 ipython?

python - Pandas DataFrame : most data in columns are 'float' , 我想删除 'str' 的行

python - 计算数据帧尾部值的序列