Python 用numpy将矩阵映射为特定向量
我有一个类似的矩阵:Python 用numpy将矩阵映射为特定向量,python,numpy,vector,Python,Numpy,Vector,我有一个类似的矩阵: 1 0 0 1 0 0 0 2 0 0 2 0 0 0 3 0 0 3 (非零数字表示我感兴趣的部分。矩阵中的实际数字可能是随机的。) 我需要生成这样的向量: [ 1 1 2 2 3 3 ].T 我可以通过循环来实现这一点: result = np.zeros([rows]) for y in range(rows): x = y // (rows // cols) # pick index of corresponded column result[
1 0 0
1 0 0
0 2 0
0 2 0
0 0 3
0 0 3
(非零数字表示我感兴趣的部分。矩阵中的实际数字可能是随机的。)
我需要生成这样的向量:
[ 1 1 2 2 3 3 ].T
我可以通过循环来实现这一点:
result = np.zeros([rows])
for y in range(rows):
x = y // (rows // cols) # pick index of corresponded column
result[y] = mat[y][x]
但我不知道如何在向量形式下实现这一点。这可能是您想要的
import numpy as np
m = np.array([
[1, 0, 0],
[1, 0, 0],
[0, 2, 0],
[0, 2, 0],
[0, 0, 3],
[0, 0, 3]
])
rows, cols = m.shape
# axis1 indices
y = np.arange(rows)
# axis2 indices
x = y // (rows // cols)
result = m[y,x]
print(result)
结果:
[1 1 2 2 3 3]
这可能是你想要的
import numpy as np
m = np.array([
[1, 0, 0],
[1, 0, 0],
[0, 2, 0],
[0, 2, 0],
[0, 0, 3],
[0, 0, 3]
])
rows, cols = m.shape
# axis1 indices
y = np.arange(rows)
# axis2 indices
x = y // (rows // cols)
result = m[y,x]
print(result)
结果:
[1 1 2 2 3 3]
怎么样
mat[mat!=0]
?>但是不是0,而是一些垃圾枚举器只是标记,它应该可以帮助您了解我要提取矩阵的哪些部分“不是0,而是一些垃圾”这是什么意思?0会带来巨大的不同。您只需要x.sum(axis=1)
示例中的行总和……我只想突出显示我感兴趣的段。你可以把矩阵中的数字想象成一些随机值。那么mat[mat!=0]
呢?>但是不是0而是有一些垃圾枚举器只是标记,它应该可以帮助你了解我想要提取矩阵的哪些部分“而不是0有一些垃圾”这是什么意思?0会带来巨大的不同。您只需要x.sum(axis=1)
示例中的行总和……我只想突出显示我感兴趣的段。你可以把矩阵中的数字想象成一些随机值。