Indexing and slicing in numpy [duplicate] - python

This question already has answers here:
Numpy slicing with bound checks
(2 answers)
Closed 2 years ago.
x = np.array([[[1],[2],[3]], [[4],[5],[6]]])
x.shape
(2,3,1)
x[1:3]
array([[[4],
[5],
[6]]])
I am expecting error in x[1:4] because index out bound but it gives output how it is possible.

>>> "hi"[1:500]
'i'
Python will adjust the end of the slice to match then end of the sequence: there are no more entries at indices 2-499, so it just stops at index 1.
>>> "what"[3000:]
''
It will also clamp the beginning of the slice to match the end of the sequence: there are no entries at index 3000, so an empty string is returned.
Same with your case: x[1] == [[4],[5],[6]]], but x[2:3] is an empty sequence, so you got [[[4],[5],[6]]]] + [] == [[[4],[5],[6]]]].

For the interval index it is the behavior of Numpy. If you give a single index (out of range) it will raise error. For Example:
x = np.array([1, 2, 3, 4, 5, 6])
x[7]
If you want to have both raise error and interval indexing you can use Numpy take:
a = [4, 3, 5, 7, 6, 8]
indices = range(3, 7)
np.take(a, indices)
in both the above cases, Numpy will raise error

Related

Is there a format in Python where I can represent any arbitrary range that I can pass to index another array?

Right now I'm using a tuple with start and end index:
ind_range = (34,98)
but what I want is:
ind_range = (34:98)
so I can pass this directly to the array:
array[ind_range]
Edit:
Original question answered: use range()
Ultimately, what I'm trying to do is index another array with a list of index ranges.
ind_ranges=[range(5,9), range(13,19)]
array[ind_ranges]
output: [[values from range1],[values from range2]]
When I do this I get the error:
IndexError: arrays used as indices must be of integer (or boolean)
type
Final Edit:
Correct answer: use a slice object in combination with a list comprehension.
You can just use a slice object.
s = slice(34, 98)
Now you can just use
array[s]
Use a list comprehension if you want to use multiple slices:
slices= [slice(34, 98), slice(34, 98), slice(34, 98)]
values = [array[s] for s in slices]
This works for me - Nicolas' solution returns TypeError: list indices must be integers or slices, not range for me in python 3
>>> arr = [i for i in range(15)]
>>> start, end = 8, 12
>>> arr[start:end]
[8, 9, 10, 11]
Literally just array[range(34, 98)].
Since you're all struggling, here's a step by step tutorial:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])
print(arr[range(2, 4)])
Out[1]: [3 4]

How to check if a numpy array contain a list of numbers? [duplicate]

This question already has answers here:
Checking if a NumPy array contains another array [duplicate]
(2 answers)
Closed 3 years ago.
I have a numpy array with another arrays inside and I want to know how I can check if all the values of another numpy array (Or list) are the same of the first one.
array1 = np.array([[11,3,4,6,7,8,9,1,2], [6,7,2,1,9,5,3,4,8]])
array2 = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
I tried to do it with the array2 in np.sort(array1) but it return True.
I want to obtain False in the first array of the array [11,3,4,6,7,8,9,1,2] because the number 5 is not in and True in the second one [1, 2, 3, 4, 5, 6, 7, 8, 9].
Thanks for taking your time to read it and trying to help.
you are currently checking to see if any of the arrays match.
if you want False and True, you need an elementwise comparison. done via a list comprehension:
[all(array2 == arr) for arr in np.sort(array1)]
which gives [False, True]
the all() is there because just checking array2 == arr will give a list of True/False for each entry, but we want a full match

How do we use 'and' operator in array indexing? [duplicate]

This question already has answers here:
How does the logical `and` operator work with integers? [duplicate]
(2 answers)
Python's Logical Operator AND [duplicate]
(7 answers)
Closed 4 years ago.
I found one code that used A[i][j] += min(A[i - 1][j and j - 1:j + 2])
I tried similar implementation as shown below which gave me unexpected results.Can anyone explain me? I am not able to understand how 'and' is interpreted in such situations.
a = [1,2,3,4,5,6,7,8,9,10,11,12]
print(a[0 and 3:4]) #[1, 2, 3, 4]
print(a[1 and 3:4]) #[4]
print(a[1 and 3:6]) #[4, 5, 6]
print(a[0 and 3:6]) #[1, 2, 3, 4, 5, 6]
print(a[2 and 3:6]) #[4, 5, 6]
edit : in a[0 and 3:4] it includes elements from 0 to 3 but if I use a[1 and 3:4] it gives only 3rd element whereas I expect elements from 1 to 3
AND has higher precedence than slice : operator.
Your expressions works as,
a[0 and 3:4] --> a[(0 and 3):4] --> a[0:4] --> [1, 2, 3, 4]
You are simply comparing integer values by "and" in your case - not the values behind the index values. If you compare anything with 0, you get 0. In all the other cases, you get the value of the second integer (Maybe not for every python interpreter).

What does this Array split syntax means in python [duplicate]

This question already has answers here:
Understanding slicing
(38 answers)
Closed 5 years ago.
(X_train, X_test) = X[50:], X[:50]
How does the split happens here? Please provide the inner explanation.
Take the following example on a simple list:
a = [0, 1, 2, 3, 4, 5, 6, 7]
print(a[:3])
print(a[3:])
Will output
[0, 1, 2]
# [:3] returns everything from the start, to before the third index
[3, 4, 5, 6, 7]
# [3:] returns everything from the third index to the end
Expanded to [50:] and [:50] will return everything from the 50th index to the end and everything from the beginning to before the 50th index respectively.
The second part of your question is about tuple unpacking. If there are the same number of variables to set as there are elements in some collection such as a tuple or list, it'll unpack them. For example:
(a, b) = 42, 9001
print("Val A:", a)
print("Val B:", b)
Will output:
Val A: 42
Val B: 9001
You actually don't even need the () brackets around the variables.
Expanded to your question, it's actually just a simplified, one line version of saying:
X_train = X[50:]
X_test = X[:50]
Assuming X is a list, tuple or an array, the first slice ([50:]) will return all the elements from the 50th element to the end. The second slice ([:50]) will return the first through the 49th element.

What are the default values for extended slice with negative and positive step [duplicate]

This question already has answers here:
What are the default slice indices *really*?
(8 answers)
Why does list[::-1] not equal list[:len(list):-1]?
(2 answers)
Closed 5 years ago.
What are the default values of start and stop in list slice? Do they change if the step is positive or negative?
For example:
a = [1,2,3,4,5,6]
print(a[::1])
>>> [1, 2, 3, 4, 5, 6]
Above code makes it look that default value of start and stop are 0 and len(a).
But if we use a step = -1
a = [1,2,3,4,5,6]
print(a[::-1])
>>> [5, 4, 3, 2, 1, 0]
Following python documenttation from https://docs.python.org/3/tutorial/introduction.html#strings
Slice indices have useful defaults; an omitted first index defaults to
zero, an omitted second index defaults to the size of the string being
sliced.
If that is the case we should get an empty list.
a = [1,2,3,4,5,6]
print(a[0:len(a):-1])
>>> []
a = "python"
a[0:len(a):-1]
>>>> ''

Categories

Resources