I want to get all but the first and last n elements from an array, can I do this while keeping consistent behaviour for n=0 without using an if statement? (Python 2.7). This does what I want, but falls apart if nCut=0:
nCut = 3
newArray = oldArray[nCut:-nCut]
This is closer, but doesn't include the last element (and is also really just a slightly hidden if statement)
newArray = oldArray[nCut:-nCut-1*(nCut<1)]
I have to do this to a bunch of arrays I'm loading from files, so not having a big ugly doubled up if
for the n=0 case would be nice.
Lowercase letters, numbers, and dashes are allowed. Have another way to solve this solution? Contribute your code (and comments) through Disqus. Previous: Write a NumPy program to extract first and second elements of the first and second rows from a given (4x4) array.
Write a NumPy program to extract all the elements of the first row from a given (4x4) array. import numpy as np arra_data = np.arange (0,16).reshape ( (4, 4)) print ("Original array:") print (arra_data) print (" Extracted data: First row") print (arra_data [0])
You can simply use take method and index of element (Last index can be -1). arr = np.array ([1,2,3]) last = arr.take (-1) # 3
- GeeksforGeeks How to get values of an NumPy array at certain index positions? Sometimes we need to remove values from the source Numpy array and add them at specific indices in the target array. In NumPy, we have this flexibility, we can remove values from one array and add them to another array.
Add len(oldArray)
yourself instead of counting on the slicing implementation to do it for you:
newArray = oldArray[nCut:len(oldArray)-nCut]
You can also use -nCut or None
to use None
as the endpoint if it would otherwise be 0
:
newArray = oldArray[nCut:-nCut or None]
None
is what a slice endpoint is set to if you don't write one in, so this is equivalent to oldArray[nCut:]
when nCut
is 0
. This is less immediately understandable, but also less verbose. It may be a better choice in cases of multidimensional slicing, or if the expression for the array is more complex than just oldArray
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With