python中的二维数组操作
我有一个2D数组,我希望每行数组中的元素I被同一行中的元素I-1减少 我尝试过以下代码:python中的二维数组操作,python,arrays,numpy,Python,Arrays,Numpy,我有一个2D数组,我希望每行数组中的元素I被同一行中的元素I-1减少 我尝试过以下代码: data = np.arange(12).reshape(3,4) print(data) for row in data: for cell in row: data[cell] = data[cell]-data[cell-1] print(data) 我得到了这样的输出 [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] Traceb
data = np.arange(12).reshape(3,4)
print(data)
for row in data:
for cell in row:
data[cell] = data[cell]-data[cell-1]
print(data)
我得到了这样的输出
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
Traceback (most recent call last):
File "D:/testing/test.py", line 55, in <module>
data[cell] = data[cell]-data[cell-1]
IndexError: index -8 is out of bounds for axis 0 with size 3
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[[1 1 1]
[1 1 1]
[1 1 1]]
主要过程是data[i]=data[i]-data[i-1]。我需要这个过程来处理超过1024x1024的海量数据,因此我需要一些高效的方法您可以对两个数组进行切片并减去:
data[:,1:] - data[:,:-1]
array([[1, 1, 1],
[1, 1, 1],
[1, 1, 1]])
或采取以下措施:
您可以对两个数组进行切片并进行减法:
data[:,1:] - data[:,:-1]
array([[1, 1, 1],
[1, 1, 1],
[1, 1, 1]])
或采取以下措施:
您想对行中的第一个元素做什么?@mrzo whatever,减少0或删除打印循环中的行和单元格以更好地了解它们的工作方式。您想对行中的第一个元素做什么?@mrzo whatever,减少0或删除打印循环中的行和单元格以更好地了解它们的工作方式。