我在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
我有一个关于 [location_id,小时] 的多索引。我有大约 60k 个位置,每个位置有 140 个小时(构成 800 万行(。
其余数据是数字(浮点数(或分类数据。我在这里只包含 2 列,通常大约有 20 列。
我愿意做的是创建一个新的数据框,它基本上是该数据框的加权平均值。要求表明,其中 12 个
location_id
应按指定的权重取平均值以形成combined_location_id
值。例如,
location_id
s 1,3,5,7,9,11,13,15,17,19,21,23 及其适当的权重(来自另一个数据框的单独数据(应从combined_location_id
CL_1
的数据中加权平均。这是很多需要处理的数据,我无法找到一种完全的熊猫解决方法。因此,我采取了
for loop
的方法。它非常慢,我相信这不是正确的方法:
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)
- 这在功能上效果很好,但是性能和内存消耗很糟糕。在我的数据集上花费了 2 个多小时,目前这是不可接受的。for 循环的存在表明可以更好地处理这个问题。
- 有没有更好/更快的方法来实现这一点?
从我所看到的情况来看,您可以使用mapped_location_ids
减少一个 for 循环
data_for_this_combined_location = df_data.loc[df_data.index.get_level_values(0).isin(mapped_location_ids)]