Python逐位对比多组同尺寸二维数组求最大值及对应日期咨询
实现方案
核心逻辑是每次仅加载1个新数组和内存中已存的当前最大值、日期数组做对比更新,内存占用仅和单个数组的尺寸相关,和总数据量无关,完全可以支撑数千个大体积数组的计算。
以下是可直接适配你需求的代码:
import numpy as np # 此处替换为你实际的日期和对应数组存储路径的映射,无需提前加载数组 date_file_map = [ ('day1', 'path/to/day1.npy'), ('day2', 'path/to/day2.npy'), ('day3', 'path/to/day3.npy'), ('day4', 'path/to/day4.npy') ] # 初始化:仅加载第一个数组作为初始基准 first_date, first_path = date_file_map[0] # 实际使用时替换为 current_max = np.load(first_path) 读取本地文件 current_max = np.array([[4, 5, 6, 8],[9, 5, 3, 5]]) current_date = np.full(current_max.shape, first_date, dtype=object) # 遍历剩余所有数组,单次仅加载一个 for date_name, file_path in date_file_map[1:]: # 实际使用时替换为 current_arr = np.load(file_path) 读取本地文件 if date_name == 'day2': current_arr = np.array([[6, 0, 0, 1],[6, 1, 8, 1]]) elif date_name == 'day3': current_arr = np.array([[5, 2, 7, 9],[4, 3, 7, 7]]) elif date_name == 'day4': current_arr = np.array([[1, 0, 0, 7],[4, 7, 7, 3]]) # 标记需要更新的位置 update_mask = current_arr > current_max # 更新最大值 current_max[update_mask] = current_arr[update_mask] # 更新对应位置的日期 current_date[update_mask] = date_name # 输出结果和你预期完全一致 highest_values = current_max date = tuple(current_date.tolist()) print(highest_values) print(date)
内容的提问来源于stack exchange,提问作者Jab
相关产品推荐
相关产品推荐

