I want to sort a numpy array of arrays based on their last entry.
For example, say we have this array of arrays:
a=np.array([np.array([1,2,5]),np.array([1,3,0]),np.array([1,4,-17])])
I want to return the array sorted this way:
np.array([np.array([1,4,-17]),np.array([1,3,0]) ,np.array([1,2,5]) ])
I.e. as -17 <= 0 <= 5, last array becomes the first one, and so on. Elements within each array must not be altered.
I suppose numpy has a builtin but I haven't been able to find it.
Related
I have an numpy array that is shape 20, 3. (So 20 3 by 1 arrays. Correct me if I'm wrong, I am still pretty new to python)
I need to separate it into 3 arrays of shape 20,1 where the first array is 20 elements that are the 0th element of each 3 by 1 array. Second array is also 20 elements that are the 1st element of each 3 by 1 array, etc.
I am not sure if I need to write a function for this. Here is what I have tried:
Essentially I'm trying to create an array of 3 20 by 1 arrays that I can later index to get the separate 20 by 1 arrays.
a = np.load() #loads file
num=20 #the num is if I need to change array size
num_2=3
for j in range(0,num):
for l in range(0,num_2):
array_elements = np.zeros(3)
array_elements[l] = a[j:][l]
This gives the following error:
'''
ValueError: setting an array element with a sequence
'''
I have also tried making it a dictionary and making the dictionary values lists that are appended, but it only gives the first or last value of the 20 that I need.
Your array has shape (20, 3), this means it's a 2-dimensional array with 20 rows and 3 columns in each row.
You can access data in this array by indexing using numbers or ':' to indicate ranges. You want to split this in to 3 arrays of shape (20, 1), so one array per column. To do this you can pick the column with numbers and use ':' to mean 'all of the rows'. So, to access the three different columns: a[:, 0], a[:, 1] and a[:, 2].
You can then assign these to separate variables if you wish e.g. arr = a[:, 0] but this is just a reference to the original data in array a. This means any changes in arr will also be made to the corresponding data in a.
If you want to create a new array so this doesn't happen, you can easily use the .copy() function. Now if you set arr = a[:, 0].copy(), arr is completely separate to a and changes made to one will not affect the other.
Essentially you want to group your arrays by their index. There are plenty of ways of doing this. Since numpy does not have a group by method, you have to horizontally split the arrays into a new array and reshape it.
old_length = 3
new_length = 20
a = np.array(np.hsplit(a, old_length)).reshape(old_length, new_length)
Edit: It appears you can achieve the same effect by rotating the array -90 degrees. You can do this by using rot90 and setting k=-1 or k=3 telling numpy to rotate by 90 k times.
a = np.rot90(a, k=-1)
I have a 2-d numpy array that I know is sorted across axis=1. Example:
[[0,0,1],
[0,7,1],
[1,1,0]]
I want to check with complexity of log(n) if the array contains a certain row, example: [0,7,1].
I thought about using search-sorted
to get the index in which the row would have to go in, and if the row is indeed in the array, it would have to be before or after this index, but can I be sure it would be one way or the other?
You can create a function that returns the index:
idxlist=[[0,0,1],[0,7,1],[1,1,0]]
def checkforindex(idxlist, idx):
return idxlist.index(idx)
print(checkforindex(idxlist, [1,1,0]))
2
I would like to access a multidimensional python array with an array of indexes, using the whole array to index the target element.
Let me explain it better:
A = np.arange(4).reshape(2,2)
a = [1,1]
>>> A[a[0],a[1]]
3
My intention is to pass the array without hard-coding the indexes values and get the same result, that is the value A[1,1]. I tried but the only way I found is working differently:
>>> A[a]
array([[2, 3],
[2, 3]])
What results is the construction of a new array where each value of the index array selects one row from the array being indexed and the resultant array has the resulting shape (number of index elements, size of row).
Thank you.
Pass a tuple (not a list) to __getitem__ (the [..] indexer).
A[tuple(a)]
3
Is there a way of computing a minimum index value of an array after application of a function (i.e. the equivalent of matlab find)?
In other words consider something like:
a = [1,-3,-10,3]
np.find_max(a,lambda x:abs(x))
Should return 2.
I could write a loop for this obviously but I assume it would be faster to use an inbuilt numpy function if one existed.
Use argmax, according to the documentation:
numpy.argmax(a, axis=None, out=None)
Returns the indices of
the maximum values along an axis.
Parameters: a : array_like Input array. axis : int, optional By
default, the index is into the flattened array, otherwise along the
specified axis. out : array, optional If provided, the result will be
inserted into this array. It should be of the appropriate shape and
dtype. Returns: index_array : ndarray of ints Array of indices into
the array. It has the same shape as a.shape with the dimension along
axis removed. See also ndarray.argmax, argmin
amax The maximum value along a given axis. unravel_index Convert a
flat index into an index tuple. Notes
In case of multiple occurrences of the maximum values, the indices
corresponding to the first occurrence are returned.
import numpy as np
a = [1, -3, -10, 3]
print(np.argmax(np.abs(a)))
Output:
2
I have a numpy array of indexes e.g. [1,3,12]. I want to create another array from this such that at these indexes, I get a non-zero elements e.g. 1. So in this case, with input [1,3,12], I should get [0,1,0,1,0,0,0,0,0,0,0,0,1]. I can do it in a for loop, is there a short numpy function to achieve this?
With numpy you can index with lists directly:
a = [1,3,12]
vector = numpy.zeros(shape=max(a) + 1)
vector[a] = 1