Insert elements from a set to an array (numpy) - python

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])

Related

numpy where on non-sorted array

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)]

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.

How to find the number of unique elements in a list of ndarrays?

I have a list of ndarrays and I want to find the number of unique ndarrays in it.
For example:
l = [ np.array([1,2,3]), np.array([2,3,4]), np.array([1,2,3]) ]
l
=> [array([1, 2, 3]), array([2, 3, 4]), np.array([1,2,3])]
np.unique(l) expected outcome:
=> [array([1, 2, 3]), array([2, 3, 4])]
When I try to use np.unique() I get TypeError: unhashable type: 'numpy.ndarray'
Can anyone suggest an efficient way to get this? (I can use map, calc some hash value from the arrays and run up.unique on that, but I'm wondering if there is a better way.)
Thanks!
You can cast the arrays to tuples:
len(set([tuple(v) for v in l]))

Duplicate numpy array rows where the number of duplications varies

Whereas there is a numpy array for which one desires to duplicate each value a specified number of times:
np.array([1,2,3,4])
and a second array definining the number of duplications desired for each corresponding index position in the original array:
np.array([3,3,2,2])
How does one produce:
[1,1,1,2,2,2,3,3,4,4]
Obviously, it is possible to use iteration to produce the new array, but I'm curious if there is a more elegant numpy-based solution.
Use numpy.repeat:
>>> numpy.repeat([1,2,3,4], [3,3,2,2])
array([1, 1, 1, 2, 2, 2, 3, 3, 4, 4])

Finding the minimum value in a numpy array and the corresponding values for the rest of that array's row

Consider the following NumPy array:
a = np.array([[1,4], [2,1],(3,10),(4,8)])
This gives an array that looks like the following:
array([[ 1, 4],
[ 2, 1],
[ 3, 10],
[ 4, 8]])
What I'm trying to do is find the minimum value of the second column (which in this case is 1), and then report the other value of that pair (in this case 2). I've tried using something like argmin, but that gets tripped up by the 1 in the first column.
Is there a way to do this easily? I've also considered sorting the array, but I can't seem to get that to work in a way that keeps the pairs together. The data is being generated by a loop like the following, so if there's a easier way to do this that isn't a numpy array, I'd take that as an answer too:
results = np.zeros((100,2))
# Loop over search range, change kappa each time
for i in range(100):
results[i,0] = function1(x)
results[i,1] = function2(y)
How about
a[np.argmin(a[:, 1]), 0]
Break-down
a. Grab the second column
>>> a[:, 1]
array([ 4, 1, 10, 8])
b. Get the index of the minimum element in the second column
>>> np.argmin(a[:, 1])
1
c. Index a with that to get the corresponding row
>>> a[np.argmin(a[:, 1])]
array([2, 1])
d. And take the first element
>>> a[np.argmin(a[:, 1]), 0]
2
Using np.argmin is probably the best way to tackle this. To do it in pure python, you could use:
min(tuple(r[::-1]) for r in a)[::-1]

Categories

Resources