我正在用Python编码。数据框full_df具有以下特征:building_id和log_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/