You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于时间分组对多维图像数组求均值的Pythonic实现方法问询

按时间分组对多维图像序列求均值的最优Python实现

下面是几种高效的实现方式,覆盖不同场景需求:

1. Numpy 显式分组(简洁易读)

适合中小规模数据,代码直观,利用numpy原生索引和均值计算:

import numpy as np

# 构造示例数据
np.random.seed(42)
N, x, y = 10, 3, 3
images = np.random.rand(N, x, y)
times = np.array([0, 0, 1, 1, 1, 2, 2, 3, 4, 4])

# 获取唯一时间值及分组索引映射
unique_times, group_indices = np.unique(times, return_inverse=True)

# 遍历每个分组计算均值
mean_images = np.array([
    images[group_indices == idx].mean(axis=0) 
    for idx in range(len(unique_times))
])

print(f"输出形状: {mean_images.shape}")  # 输出 (5, 3, 3),对应5个唯一时间的均值图像

2. Pandas GroupBy(贴近分组操作习惯)

如果你习惯pandas的分组语法,这种方式更符合groupby.agg的使用直觉:

import pandas as pd
import numpy as np

# 构造示例数据
np.random.seed(42)
N, x, y = 10, 3, 3
images = np.random.rand(N, x, y)
times = np.array([0, 0, 1, 1, 1, 2, 2, 3, 4, 4])

# 将图像展平为一维,和时间字段组成DataFrame
df = pd.DataFrame({
    "time": times,
    "image": [img.flatten() for img in images]
})

# 分组求均值后恢复图像形状
grouped_result = df.groupby("time")["image"].apply(
    lambda arr: np.mean(arr.tolist(), axis=0).reshape(x, y)
)
mean_images = np.array(grouped_result.tolist())

print(f"输出形状: {mean_images.shape}")

3. Numpy 高效分组求和(超大数据量最优)

针对百万级以上的N,用np.add.at实现无循环分组求和,再除以组内元素个数,效率远高于显式循环:

import numpy as np

# 构造示例数据
np.random.seed(42)
N, x, y = 10, 3, 3
images = np.random.rand(N, x, y)
times = np.array([0, 0, 1, 1, 1, 2, 2, 3, 4, 4])

unique_times, group_indices = np.unique(times, return_inverse=True)
n_unique = len(unique_times)

# 计算每个分组的元素个数,扩展维度以便广播
group_counts = np.bincount(group_indices).reshape(n_unique, 1, 1)

# 初始化求和数组,用add.at高效累加每个分组的图像
sum_images = np.zeros((n_unique, x, y))
np.add.at(sum_images, group_indices, images)

# 求和后除以个数得到均值
mean_images = sum_images / group_counts

print(f"输出形状: {mean_images.shape}")

场景选择建议

  • 中小数据量:优先选Numpy显式分组或Pandas方法,代码简洁易维护;
  • 超大数据量:必须用Numpy高效分组求和,避免循环带来的性能损耗;
  • 已有Pandas工作流:直接用Pandas GroupBy,和现有代码风格统一。

内容的提问来源于stack exchange,提问作者yankeefan11

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 14:50:26