如何根据另一列表的唯一值对数值列表按索引匹配求和?
按分组对对应数值求和的解决方案
针对你的需求,这里提供几种高效的实现方式,结合你已经用到的numpy工具,也补充纯Python的实现方法:
方法一:利用numpy的return_inverse快速分组求和
这种方法直接通过numpy的内置函数完成分组,效率最高:
import numpy as np list_one = ["A", "A", "B", "B", "C", "C"] list_two = [1000, 200, 500, 120, 500, 350] # 转换为numpy数组方便操作 arr_one = np.array(list_one) arr_two = np.array(list_two) # 获取唯一值列表,以及原数组每个元素对应的唯一值下标 unique_vals, inverse_idx = np.unique(arr_one, return_inverse=True) # 按分组下标求和,weights参数指定对应数值 sum_vals = np.bincount(inverse_idx, weights=arr_two) # 转换为整数列表(如果需要) res_list = [int(val) for val in sum_vals] print(res_list) # 输出: [1200, 620, 850]
方法二:基于你已获取的唯一值索引实现
如果你想继续使用之前拿到的unique_indices,可以通过布尔索引筛选对应元素求和:
import numpy as np list_one = ["A", "A", "B", "B", "C", "C"] list_two = [1000, 200, 500, 120, 500, 350] arr_one = np.array(list_one) arr_two = np.array(list_two) # 获取唯一值和首次出现的索引(你已经拿到的结果) unique_vals, unique_indices = np.unique(arr_one, return_index=True) res_list = [] for val in unique_vals: # 筛选所有等于当前分组键的元素,求和对应数值 group_sum = arr_two[arr_one == val].sum() res_list.append(group_sum) print(res_list) # 输出: [1200, 620, 850]
方法三:纯Python字典实现(无需numpy)
如果不想依赖numpy,用普通字典也能轻松实现:
list_one = ["A", "A", "B", "B", "C", "C"] list_two = [1000, 200, 500, 120, 500, 350] sum_dict = {} # 遍历配对的键和数值,累加求和 for key, num in zip(list_one, list_two): sum_dict[key] = sum_dict.get(key, 0) + num # 按键的升序生成结果列表(和numpy的unique结果顺序一致) res_list = [sum_dict[key] for key in sorted(sum_dict.keys())] print(res_list) # 输出: [1200, 620, 850]
内容的提问来源于stack exchange,提问作者Steven01123581321
相关产品推荐
相关产品推荐

