首页 > 解决方案 > 大数据框中的 Pandas 加权平均方式

问题描述

我在 Pandas 中确实有一个大型数据集(大约 800 万行 x 25 列),我正在努力寻找一种方法来计算这个数据帧的加权平均值,从而创建另一个数据帧。

这是我的数据集的样子(非常简化的版本):

                   prec     temp
location_id hours             
135         1      12.0      4.0
            2      14.0      4.1
            3      14.3      3.5
            4      15.0      4.5
            5      15.0      4.2
            6      15.0      4.7
            7      15.5      5.1
136         1      12.0      4.0
            2      14.0      4.1
            3      14.3      3.5
            4      15.0      4.5
            5      15.0      4.2
            6      15.0      4.7
            7      15.5      5.1
def __weighted(self, ds, weights):
  return np.average(ds, weights=weights)

f = {'hours': 'first', 'location_id': 'first', 
'temp': lambda x: self.__weighted(x, weights), 'prec': lambda x: self.__weighted(x, weights)}

data_frames = []
for combined_location in all_combined_locations:
   mapped_location_ids = combined_location.location_ids
   weights = combined_location.weights_of_location_ids
   data_for_this_combined_location = pd.concat(df_data.loc[df_data.index.get_level_values(0) == location_id] for location_id in mapped_location_ids)
   data_grouped_by_distance = data_for_this_combined_location.groupby("hours", as_index=False)
   data_grouped_by_distance = data_grouped_by_distance.agg(f)
   data_frames.append(data_grouped_by_distance)

df_combined_location_data = pd.concat(data_frames)
df_combined_location_data.set_index(['location_id', 'hours'], inplace=True)


标签: pythonpandasperformance

解决方案


从我看到你可以减少一个 for 循环mapped_location_ids

data_for_this_combined_location = df_data.loc[df_data.index.get_level_values(0).isin(mapped_location_ids)]

推荐阅读