简体   繁体   English

将数组元素插入矩阵

[英]Insert array elements into matrix

How can the elements from (take only range 3 to 8) 元素如何从(仅取值3到8)

a = np.array([1,2,3,4,5,6,7,8,9])

go to

A = np.array([[0,0,0],
              [0,0,0]])

Ideal output would be: 理想的输出为:

A = ([[3,4,5],
      [6,7,8]])
np.arange(3, 9).reshape((2, 3))  

outputs 输出

array([[3, 4, 5],
       [6, 7, 8]])

A possible technique, presuming that you have an existing numpy array a is to use slicing and reshaping : 假设您已有一个numpy数组a ,一种可能的技术是使用slicingreshaping

Starting array 起始数组

>>> a = np.array([1,2,3,4,5,6,7,8,9])
>>> a
array([1, 2, 3, 4, 5, 6, 7, 8, 9])

Slicing 切片

>>> A = a[2:-1]
>>> A
array([3, 4, 5, 6, 7, 8])

Reshaping 重塑

>>> A.reshape((2, 3))
>>> A
array([[3, 4, 5],
       [6, 7, 8]])

The above solution presumes that you know which index to choose when doing the slicing. 上面的解决方案假定您知道在进行切片时要选择哪个索引。 In this case, I presumed that we knew that the element 3 occurs at the second index position and I presumed that we knew that the last desired element 8 occurred in the second to last position in the array (at index -1 ). 在这种情况下,我假设我们知道元素3出现在第二个索引位置,并且我假设我们知道最后一个所需的元素8出现在数组中倒数第二个位置(在索引-1 )。 For clarity's sake: slicing starts at the given index, but goes up to and not including the second index position AND it is often easier to find the index position close to the end of the list by counting backwards using negative index numbers as I have done here. 为了清楚起见:切片从给定的索引开始,但一直延伸到第二个索引位置(不包括该位置),并且像我一样,通过使用负索引号向后计数,通常更容易找到靠近列表末尾的索引位置这里。 An alternate would be to use the index position of the last element which is an 8 : 另一种方法是使用最后一个元素的索引位置8

A = a[2:8] . A = a[2:8]

A one-liner solution would be to daisy-chain the method calls together: 单线解决方案是将方法调用以菊花链方式链接在一起:

Starting array 起始数组

>>> a = np.array([1,2,3,4,5,6,7,8,9])
>>> a
array([1, 2, 3, 4, 5, 6, 7, 8, 9])

Slicing and reshaping 切片和整形

>>> A = a[2:-1].reshape((2, 3))
>>> A
array([[3, 4, 5],
       [6, 7, 8]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM