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

Python中向2D矩阵指定索引赋值并累加的问题求助

问题

我在Python中运行代码得到了不符合预期的结果。我的目标是向2D矩阵的对应元素赋予常量值,拥有行索引列表和列索引列表:

idx_container_phi = [22, 19, 25, 23, 22, 21, 22, 30, 16, 12, 14] # 行索引
idx_container_theta = [22, 19, 10, 23, 22, 7, 22, 8, 16, 19, 11] # 列索引
thickness = 0.85
sphere_pixels  = 36

已执行的操作:

  1. 初始化指定形状的2D矩阵:
matrix_thickness = np.array([ [0]*sphere_pixels for i in range(sphere_pixels)])
  1. 循环遍历索引列表,为对应位置赋值:
for j in range(len(idx_container_phi)):
    matrix_thickness[idx_container_phi[j]-1][idx_container_theta[j]-1] = matrix_thickness[idx_container_phi[j]-1][idx_container_theta[j]-1] + thickness

但运行后矩阵所有元素均为0(看起来像null)。需要实现向2D矩阵的每个指定索引位置赋予常量值,同一索引多次出现时累加该值(比如[22,22]出现三次,值为0.85×3=2.55),最终得到36×36的矩阵。

解决方案

问题根源

你初始化的矩阵是整数类型(dtype=int),累加浮点数0.85时会被自动截断为整数,导致所有位置的值始终为0。另外,手动循环在numpy中效率较低,推荐使用numpy原生方法。

方法一:修正循环逻辑(兼容原思路)

先将矩阵初始化为浮点类型,再执行循环:

import numpy as np

idx_container_phi = [22, 19, 25, 23, 22, 21, 22, 30, 16, 12, 14]
idx_container_theta = [22, 19, 10, 23, 22, 7, 22, 8, 16, 19, 11]
thickness = 0.85
sphere_pixels = 36

# 初始化为浮点类型矩阵,避免数值截断
matrix_thickness = np.zeros((sphere_pixels, sphere_pixels), dtype=np.float64)

# 用zip同时遍历行、列索引,代码更简洁
for phi, theta in zip(idx_container_phi, idx_container_theta):
    # 转换为numpy的0-based索引
    matrix_thickness[phi-1, theta-1] += thickness

方法二:numpy高效向量化操作(推荐)

利用np.add.at可以直接对多个索引位置批量累加,无需循环,效率更高:

import numpy as np

idx_container_phi = [22, 19, 25, 23, 22, 21, 22, 30, 16, 12, 14]
idx_container_theta = [22, 19, 10, 23, 22, 7, 22, 8, 16, 19, 11]
thickness = 0.85
sphere_pixels = 36

# 转换为numpy的0-based索引数组
rows = np.array(idx_container_phi) - 1
cols = np.array(idx_container_theta) - 1

matrix_thickness = np.zeros((sphere_pixels, sphere_pixels), dtype=np.float64)
# 对指定位置批量累加thickness
np.add.at(matrix_thickness, (rows, cols), thickness)

结果验证

以原索引[22,22]为例,转换为0-based索引是(21,21),执行后该位置的值为2.55,符合累加三次的预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 01:16:08