numpy where on non-sorted array - python

I want to find the indices of the elements in a numpy array which matches a list. My array is not sorted. As of now, I am using the below code
Y = np.array([ 2,2,1,1,3,1,3,2,-1,-1])
indcs = [np.where(Y == c)[0] for c in range(1,4)]
indcs
[array([2, 3, 5]), array([0, 1, 7]), array([4, 6])]
But I feel like there will be a better approach to get the result for each value to be searched as rows than simply iterating using a for loop. Can anyone help?

This code may help you.
indices=[i for i,v in enumerate(Y.tolist()) if v in range(0,4)]

Related

How to calculate the difference b/w each element in an numpy array with a shape[0]>2

Please feel free to let me know whether it is a duplicate question.
From
in_arr1 = np.array([[2,0], [-6,0], [3,0]])
How can I get:
diffInElements = [[5,0]] ?
I tried np.diff(in_arr1, axis=0) but it does not generate what I want.
is there a NumPy function I can use ?
Cheers,
You can negate and then sum all but the first value, and then add the first value:
diff = (-a[1:]).sum(axis=0) + a[0]
Output:
>>> diff
array([5, 0])
You want to subtract the remaining rows from the first row. The straightforward answer does just that:
>>> arr = np.array([[2, 1], [-6, 3], [3, -4]])
>>> arr[0, :] - arr[1:, :].sum(0)
array([5, 2])
There is also, however, a more advanced option making use of the somewhat obscure reduce() method of numpy ufuncs:
>>> np.subtract.reduce(arr, axis=0)
array([5, 2])

Calculation on list of numpy array

I'm trying to do some calculation (mean, sum, etc.) on a list containing numpy arrays.
For example:
list = [array([2, 3, 4]),array([4, 4, 4]),array([6, 5, 4])]
How can retrieve the mean (for example) ?
In a list like [4,4,4] or a numpy array like array([4,4,4]) ?
Thanks in advance for your help!
EDIT : Sorry, I didn't explain properly what I was aiming to do : I would like to get the mean of i-th index of the arrays. For example, for index 0 :
(2+4+6)/3 = 4
I don't want this :
(2+3+4)/3 = 3
Therefore the end result will be
[4,4,4] / and not [3,4,5]
If L were a list of scalars then calculating the mean could be done using the straight forward expression:
sum(L) / len(L)
Luckily, this works unchanged on lists of arrays:
L = [np.array([2, 3, 4]), np.array([4, 4, 4]), np.array([6, 5, 4])]
sum(L) / len(L)
# array([4., 4., 4.])
For this example this happens to be quitea bit faster than the numpy function
np.mean
timeit(lambda: np.mean(L, axis=0))
# 13.708808058872819
timeit(lambda: sum(L) / len(L))
# 3.4780975924804807
You can use a for loop and iterate through the elements of your array, if your list is not too big:
mean = []
for i in range(len(list)):
mean.append(np.mean(list[i]))
Given a 1d array a, np.mean(a) should do the trick.
If you have a 2d array and want the means for each one separately, specify np.mean(a, axis=1).
There are equivalent functions for np.sum, etc.
https://docs.scipy.org/doc/numpy/reference/generated/numpy.mean.html
https://docs.scipy.org/doc/numpy/reference/generated/numpy.sum.html
You can use map
import numpy as np
my_list = [np.array([2, 3, 4]),np.array([4, 4, 4]),np.array([6, 5, 4])]
np.mean(my_list,axis=0) #[4,4,4]
Note: Do not name your variable as list as it will shadow the built-ins

Divide numpy array into multiple arrays using indices array (Python)

I have an array:
a = [1, 3, 5, 7, 29 ... 5030, 6000]
This array gets created from a previous process, and the length of the array could be different (it is depending on user input).
I also have an array:
b = [3, 15, 67, 78, 138]
(Which could also be completely different)
I want to use the array b to slice the array a into multiple arrays.
More specifically, I want the result arrays to be:
array1 = a[:3]
array2 = a[3:15]
...
arrayn = a[138:]
Where n = len(b).
My first thought was to create a 2D array slices with dimension (len(b), something). However we don't know this something beforehand so I assigned it the value len(a) as that is the maximum amount of numbers that it could contain.
I have this code:
slices = np.zeros((len(b), len(a)))
for i in range(1, len(b)):
slices[i] = a[b[i-1]:b[i]]
But I get this error:
ValueError: could not broadcast input array from shape (518) into shape (2253412)
You can use numpy.split:
np.split(a, b)
Example:
np.split(np.arange(10), [3,5])
# [array([0, 1, 2]), array([3, 4]), array([5, 6, 7, 8, 9])]
b.insert(0,0)
result = []
for i in range(1,len(b)):
sub_list = a[b[i-1]:b[i]]
result.append(sub_list)
result.append(a[b[-1]:])
You are getting the error because you are attempting to create a ragged array. This is not allowed in numpy.
An improvement on #Bohdan's answer:
from itertools import zip_longest
result = [a[start:end] for start, end in zip_longest(np.r_[0, b], b)]
The trick here is that zip_longest makes the final slice go from b[-1] to None, which is equivalent to a[b[-1]:], removing the need for special processing of the last element.
Please do not select this. This is just a thing I added for fun. The "correct" answer is #Psidom's answer.

Insert elements from a set to an array (numpy)

I have a set (S) of numbers and I want to put this numbers in an array (arr) . I tried this code
Arr = np.array(S)
but I can't access to arrays element, for example if I try
Arr[0]
, I get this error:
IndexError: too many indices for array
Can anyone explain what is the problem with this approach and is there any other way that I can use in order to put the elements of set in array and access to them?
Thanks
You first need to convert your set of numbers to a list.
S = {1, 2, 3}
>>> np.array(S)
array(set([1, 2, 3]), dtype=object)
>>> np.array(list(S))
array([1, 2, 3])

N dimensional arrays - Python/Numpy

just wondering if there is any clever way to do the following.
I have an N dimensional array representing a 3x3 grid
grid = [[1,2,3],
[4,5,6],
[7,8,9]]
In order to get the first row I do the following:
grid[0][0:3]
>> [1,2,3]
In order to get the first column I would like to do something like this (even though it is not possible):
grid[0:3][0]
>> [1,4,7]
Does NumPy support anything similar to this by chance?
Any ideas?
Yes, there is something like that in Numpy:
import numpy as np
grid = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
grid[0,:]
# array([1, 2, 3])
grid[:,0]
# array([1, 4, 7])
You can use zip to transpose a matrix represented as a list of lists:
>>> zip(*grid)[0]
(1, 4, 7)
Anything more than just that, and I'd use Numpy.
To get the columns in Python you could use:
[row[0] for row in grid]
>>> [1,4,7]
You could rewrite your code for getting the row as
grid[0][:]
because [:] just copies the whole array, no need to add the indices.
However, depending on what you want to achieve, I'd say it's better to just write a small matrix class to hide this implementation stuff.

Categories

Resources