问题描述
如何使用 numpy 而不 使用函数作为 reshape
或 .T
或 reverse
并纯粹通过使用 for 循环或列表理解?
下面是我想问的一个例子:
我该如何转换:
[[ 1. 5. 9.]
[ 2. 6. 10.]
[ 3. 7. 11.]
[ 4. 8. 12.]]
为此:
[[ 1. 8. 9.]
[ 2. 7. 10.]
[ 3. 6. 11.]
[ 4. 5. 12.]]
这是我目前编写的代码:
import numpy as np
arr= np.ones((4,3))
for i in range(4):
for j in range(3):
arr[i,j]+=i
arr[i,j]+=j*5
print(arr)
解决方法
不使用 numpy
函数来反转奇数列,您可以执行以下操作:
import numpy as np
# just your input data
mat = np.arange(1.0,13.0).reshape(3,4).T
mat_no_numpy = np.zeros_like(mat)
rows,cols = mat.shape
for i in range(rows):
for j in range(cols):
if j % 2 == 0:
mat_no_numpy[i,j] = mat[i,j]
else:
# flip row-coordinate for odd columns
mat_no_numpy[i,j] = mat[rows - i - 1,j]
print(mat_no_numpy)
# [[ 1. 8. 9.]
# [ 2. 7. 10.]
# [ 3. 6. 11.]
# [ 4. 5. 12.]]
或者,如果允许使用 numpy
函数,您可以结合使用切片和 np.flip
来翻转每个奇数列:
import numpy as np
# just your input data
mat = np.arange(1.0,4).T
mat[:,1::2] = np.flip(mat[:,1::2])
print(mat)
# [[ 1. 8. 9.]
# [ 2. 7. 10.]
# [ 3. 6. 11.]
# [ 4. 5. 12.]]