python - 大数据框中的 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
我在 [location_id, hours] 上有一个多索引。我有大约 60k 个位置和每个位置 140 小时(构成 800 万行)。
其余数据是数字(浮点数)或分类数据。我这里只包含了 2 列,通常有 20 列左右。
我愿意做的是创建一个新的数据框,基本上是这个数据框的加权平均值。要求表明,这些
location_id
s 中的 12 个应按指定的权重平均以形成combined_location_id
值。例如,
location_id
s 1,3,5,7,9,11,13,15,17,19,21,23 及其适当的权重(来自另一个数据框的单独数据)应加权平均combined_location_id
CL_1
到数据。这是需要处理的大量数据,我无法找到完全解决问题的 Pandas 方法。因此,我采取了一种
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 循环的存在表明这可以得到更好的处理。
- 有没有更好/更快的方法来实现这一点?
解决方案
从我看到你可以减少一个 for 循环mapped_location_ids
data_for_this_combined_location = df_data.loc[df_data.index.get_level_values(0).isin(mapped_location_ids)]
推荐阅读
- bash - 在执行 docker build > CMD 时重定向 stdout 和 stderr
- javascript - 在不同浏览器中将UTC时间转换为本地时间
- php - 前端订单详情中的 API 跟踪代码集成 (Woocommerce)
- webix - 日期格式 webix 数据表过滤器
- swift - SideMenu 单独出现在更新的 macOS catalina 和更新的 Xcode 11.2.1 中
- node.js - Apollo Server Express + 订阅错误
- hadoop - 为 oozie 工作流设置 ipc.client.connect.timeout
- dynamics-crm - Dynamics Web API - 刷新令牌
- flutter - RangeError(索引):无效值:有效值范围为空:-1
- asp.net-core - 如何通过配置将 IHttpContextAccessor 传递给 Serilog Enricher