前言
不知不觉间,Python最新版本已经到了3.12.0了,然而我的版本还是3.7.7,按理说Python是向下兼容的,但是Python 3.10与旧版本之间索引赋值方面还是出现了不兼容的情况。
1 问题
直接上代码,下面是我报错的代码。下面的代码作用是根据train_indices索引将gt中的值赋值给train_gt相同位置上。
train_indices = [list(t) for t in zip(*train_indices)]
train_gt[train_indices] = gt[train_indices]
这个代码现在比较难以理解,直接创建相应的矩阵,以实例进行解释。
import numpy as np # 假设 gt 和 train_gt 的维度都是 (100, 200)
gt = np.random.random((100, 200)) #创建一个(100, 200) 随机数矩阵
train_gt = np.zeros((100, 200)) #创建一个(100, 200) 0矩阵
train_indices = [(55, 102), (60, 155), (90, 196)] #自定义一个索引
train_indices = [list(t) for t in zip(*train_indices)] #运行上边的第一行代码
print(train_indices)
#[[55, 60, 90], [102, 155, 196]] 这是打印出的结果
train_gt[train_indices] = gt[train_indices] #然后运行上边的第二行代码
在Python 3.7中运行上边的代码是没问题的,但是他提示了下边的FutureWarning,因为我是直接搬到Python 3.10运行的,因此在Python 3.10就直接报了索引错误,如下边第二个片段。
# FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`. In the future this will be interpreted as an array index, `arr[np.array(seq)]`, which will result either in an error or a different result. train_gt[train_indices] = gt[train_indices]
# IndexError: index 102 is out of bounds for axis 0 with size 100
2 解决方案
只需要修改一行代码即可解决上述代码,如果当时要是早看到FutureWarning,估计解决这个问题更简单。
train_indices = tuple(list(t) for t in zip(*train_indices)) #修改的代码
后记
大家如果有地信遥感方面的问题需要请教或者有项目需要合作,可以在闲 鱼软件的用户中搜索:遥感GIS工作室,请认准头像,谢谢。