访问矩阵中的特定元素

时间:2017-02-08 08:58:46

标签: python matrix

我是Python的新手,我的问题涉及在矩阵中获取特定元素并使用这些元素创建新矩阵。我试图这样做。

import numpy as np

a = [[  1,   2,   3, 4, 5],
 [  6,   7,   8, 9, 10],
 [  11,  12,  13, 14, 15],
 [  16,   17, 18, 19, 20],
 [  21,   22, 23, 24, 25]]

b = np.array(a)

我想只获得此矩阵的第1列和第3列,然后将它们组合以创建新矩阵。我尝试在下面添加以下代码:

newList = []

for i in range(len(b-1)):
    newList.append(b[i,0])+ newList.append(b[i,2])

但我收到了以下错误:

TypeError:+:' NoneType'不支持的操作数类型和' NoneType'

2 个答案:

答案 0 :(得分:0)

您可以使用diagonal()作为初始问题:

import numpy as np

a = np.matrix([[1 , 2 , 3 , 4 , 5 ],
               [6 , 7 , 8 , 9 , 10],
               [11, 12, 13, 14, 15],
               [16, 17, 18, 19, 20],
               [21, 22, 23, 24, 25]])

print(a.diagonal())

<强>输出:

[[ 1  7 13 19 25]]

至于您在评论中的问题,您可以将第一列和第三列组合在一起:

first_column = (a[:,0]) 
third_column = (a[:,2])

print(first_column + third_column)

<强>输出:

[[ 4]
 [14]
 [24]
 [34]
 [44]]

由于您现在想要一行,只需拨打transpose()

print((first_column + third_column).transpose())

<强>输出:

[[ 4 14 24 34 44]]

答案 1 :(得分:0)

我正在使用您的输入内容

import numpy as np

a = [[  1,   2,   3, 4, 5],
 [  6,   7,   8, 9, 10],
 [  11,  12,  13, 14, 15],
 [  16,   17, 18, 19, 20],
 [  21,   22, 23, 24, 25]]

b = np.array(a)

col_1=b[:,0] #Slicing first column
col_3=b[:,2] #Slicing third column

new_mat=np.matrix([col_1,col_3]) #Creates a matrix with col_1 as 1st row and col_3 as second row
new_mat=np.transpose(new_mat)

输出:

matrix([[ 1,  3],
        [ 6,  8],
        [11, 13],
        [16, 18],
        [21, 23]])

希望这会有所帮助