How can the elements from (take only range 3 to 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
:
>>> a = np.array([1,2,3,4,5,6,7,8,9])
>>> a
array([1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> A = a[2:-1]
>>> A
array([3, 4, 5, 6, 7, 8])
>>> 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
). 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
:
A = a[2:8]
.
A one-liner solution would be to daisy-chain the method calls together:
>>> a = np.array([1,2,3,4,5,6,7,8,9])
>>> a
array([1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> A = a[2:-1].reshape((2, 3))
>>> A
array([[3, 4, 5],
[6, 7, 8]])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.