I have a 4d array to mask and a 2d array to mask index.
i should masking ndarray data using 2d array indices and i dont want to using for-loop.
how should i do?
for example,
mask_arr = np.random.rand(5,10,100)
idx_arr = np.random.randint(10, size=(5,5))
and my masking code like this using for-loop
mask_val = 0
for i in range(5):
mask_arr[i, idx_arr[i],:] = mask_val
Related
How do you get indexing [::-1] to reverse ALL 2D array rows and ALL 3D and 4D array columns and rows simultaneously? I can only get indexing [::-1] to reverse 2D array columns. Python
import numpy as np
randomArray = np.round(10*np.random.rand(5,4))
sortedArray = np.sort(randomArray,axis=1)
reversedArray = sortedArray[::-1]
# reversedArray = np.flip(sortedArray,axis=1)
print('Random Array:')
print(randomArray,'\n')
print('Sorted Array:')
print(sortedArray,'\n')
print('Reversed Array:')
print(reversedArray)
You can reverse a dimensions of a numpy array depending on where you place the ::-1.
Lets take a 3D array. For reversing the first dimension:
reversedArray = sortedArray[::-1,:,:]
For reversing the second dimension:
reversedArray = sortedArray[:,::-1,:]
For reversing the third dimension:
reversedArray = sortedArray[:,:,::-1]
I'm looking to create a numpy array of d dimensions, where each dimension is of length n.
For example:
np.zeros((5,2)), will give me a 5-row, 2-column array of zeros. What I'm looking for is a 5x5 array. Now I know I can simply do np.zeros((5,5)), but my goal is to generate the array dynamically:
dims = 4
elem_length = 10
#generate the array
#results in a 10x10x10x10 numpy array
Another option is to create single-dimensional tuples and join them all:
shp = ()
for i in range(dims):
shp = shp + (elem_length,)
new_arr = np.zeros(shp)
But that's not python-y at all. Is there a better way?
I'm not sure about numpy way to generate a dxdxdx... array, but if you wanted to generate the shape tuple you could try list comprehension.
EX:
shape_list = [elem_length for _ in range(dims)]
shape_tuple = tuple(shape_list)
print(shape_tuple)
>> (elem_length, elem_length, elem_length)
dn_arr = np.zeros(shape_tuple)
print(dn_arr.shape)
>> (elem_length, elem_length, elem_length)
I have a ndarray of shape (68, 64, 64) called 'prediction'. These dimensions correspond to image_number, height, width. For each image, I have a tuple of length two that contains coordinates that corresponds to a particular location in each 64x64 image, for example (12, 45). I can stack these coordinates into another Numpy ndarray of shape (68,2) called 'locations'.
How can I construct a slice object or construct the necessary advanced indexing indices to access these locations without using a loop? Looking for help on the syntax. Using pure Numpy matrixes without loops is the goal.
Working loop structure
Import numpy as np
# example code with just ones...The real arrays have 'real' data.
prediction = np.ones((68,64,64), dtype='float32')
locations = np.ones((68,2), dtype='uint32')
selected_location_values = np.empty(prediction.shape[0], dtype='float32')
for index, (image, coordinates) in enumerate(zip(prediction, locations)):
selected_locations_values[index] = image[coordinates]
Desired approach
selected_location_values = np.empty(prediction.shape[0], dtype='float32')
correct_indexing = some_function_here(locations). # ?????
selected_locations_values = predictions[correct_indexing]
A straightforward indexing should work:
img = np.arange(locations.shape[0])
r = locations[:, 0]
c = locations[:, 1]
selected_locations_values = predictions[img, r, c]
Fancy indexing works by selecting elements of the indexed array that correspond to the shape of the broadcasted indices. In this case, the indices are quite straightforward. You just need the range to tell you what image each location corresponds to.
I have a 3d array where all axis lengths are the same (for example (5,5,5)). I need to mask all of the array and keep certain slices in the array unmasked as per the code below. I managed to accomplish this using a for loop but I wondered if there was a faster solution out there.
array = np.reshape(np.array(np.random.rand(125)), (5,5,5))
array = ma.array(array, mask=True)
for i in range(array.shape[0]):
for j in range(array.shape[1]):
array[i, j, :].mask[i:j] = False
This allows me to sum this array with another array of the same size while ignoring the masked values.
You can create the entire mask in one step using broadcasting:
i, j, k = np.ogrid[:5, :5, :5]
mask = (i>k) | (k>=j)
I have a 3D numpy array (1L, 420L, 580L) the 2nd and 3rd dimension is a gray scale image that I want to display using openCV. How do I pull the 2D array from the 3D array?
I created a short routine to do this, but I bet there is a better way.
# helper function to remove 1st dimension
def pull_image(in_array):
rows = in_array.shape[1] # vertical
cols = in_array.shape[2] # horizontal
out_array = np.zeros((rows, cols), np.uint8) # create new array to hold image data
for r in xrange(rows):
for c in xrange(cols):
out_array[r, c] = in_array[:, r, c]
return out_array
If you always only have the first dimension == 1, then you could simply reshape the array...
if in_array.shape[0] == 1:
return in_array.reshape(in_array.shape[1:])
otherwise, you can use numpy's advanced list slicing...
else:
return in_array[0,:,:]