How to add the indices (x,y) of array elements (u,v) to get an array of elements (x,y,u,v)?
numpy array operations
numpy array shape
numpy arrays are immutable
I wrote a function that adds the indices of each element in the array to the elements.
First element is [10,11], index is [0,0] -> Becomes [0,0,10,11]
Second element is [12,13], index is [1,0] -> Becomes [1,0,12,13]
How can I optimize this function? Is there a simpler way to write it? Any improvements/recommendations will be appreciated!
My project: I am using Optical Flow to get an array of magnitudes (u, v), which represent the optical flow vector components of each pixel. I would like to add the position (x,y) of the pixels to the array so that I get an array of (x, y, u, v). Note: (x,y) position is the same as the index value, which makes it a bit easier.
Here's my code:
def vec_4D (mag_2D): vec_4D = np.zeros((mag_2D.shape,mag_2D.shape,4)) x = 0 y = 0 for row in vec_4D: for col in row: col = x col = y col = mag_2D[y][x] col = mag_2D[y][x] x += 1 x=0 y+=1 return(vec_4D) mag_2D = np.array([[[10,11], [12,13], [14,15]], [[16,17], [18,19], [20,21]]]) print(vec_4D(mag_2D))
Input array: [[[10 11] [12 13] [14 15]] [[16 17] [18 19] [20 21]]] Output array: [[[ 0. 0. 10. 11.] [ 1. 0. 12. 13.] [ 2. 0. 14. 15.]] [[ 0. 1. 16. 17.] [ 1. 1. 18. 19.] [ 2. 1. 20. 21.]]]
Here's a "multi-liner", using
y_indices,x_indices = np.indices(mag_2D.shape[0:2]) vec_4D_result = np.concatenate((x_indices[:,:,None], y_indices[:,:,None], mag_2D[y_indices,x_indices]), axis = -1)
Testing it out:
import numpy as np mag_2D = np.array([[[10,11], [12,13], [14,15]], [[16,17], [18,19], [20,21]]]) y_indices,x_indices = np.indices(mag_2D.shape[0:2]) vec_4D_result = np.concatenate((x_indices[:,:,None], y_indices[:,:,None], mag_2D[y_indices,x_indices]), axis = -1) print (vec_4D_result)
[[[ 0 0 10 11] [ 1 0 12 13] [ 2 0 14 15]] [[ 0 1 16 17] [ 1 1 18 19] [ 2 1 20 21]]]
1.4.1. The NumPy array object — Scipy lecture notes, Creating arrays; Basic data types; Basic visualization; Indexing and slicing Create a memory-map to an array stored in a *binary* file on disk. b = np.array ([[0, 1, 2], [3, 4, 5]]) # 2 x 3 array You may have noticed that, in some instances, array elements are displayed with a trailing dot (e.g. 2. vs 2 ). plt.plot(x, y) # line plot. The task is to print all indices of this array such that after removing the i th element from the array, the array becomes a good array. Note : An array is good if there is an element in the array that equals to the sum of all other elements.
Here is the inevitable one liner.
>>> np.concatenate([np.moveaxis(np.indices(mag_2D.shape[:-1]), 0, -1)[..., ::-1], mag_2D], -1) array([[[ 0, 0, 10, 11], [ 1, 0, 12, 13], [ 2, 0, 14, 15]], [[ 0, 1, 16, 17], [ 1, 1, 18, 19], [ 2, 1, 20, 21]]])
The easiest way to understand this is to break it down:
np.indices creates indices from shape
>>> np.indices(mag_2D.shape[:-1]) array([[[0, 0, 0], [1, 1, 1]], [[0, 1, 2], [0, 1, 2]]])
These are, however, separate for each dimension. To get coordinate "tuples" we must move the leading axis to the end:
>>> np.moveaxis(np.indices(mag_2D.shape[:-1]), 0, -1) array([[[0, 0], [0, 1], [0, 2]], [[1, 0], [1, 1], [1, 2]]])
y, x, OP wants
>>> np.moveaxis(np.indices(mag_2D.shape[:-1]), 0, -1)[..., ::-1] array([[[0, 0], [1, 0], [2, 0]], [[0, 1], [1, 1], [2, 1]]])
Quickstart tutorial — NumPy v1.20.dev0 Manual, One can create or specify dtype's using standard Python types. For example, an array of elements of type float64 has itemsize 8 (=64/8), while x = np. linspace( 0, 2*pi, 100 ) # useful to evaluate function at lots of points Multidimensional arrays can have one index per axis. np.trace(u) # trace 2.0 >> > y = np.array([[5.]� Examples. The example calls the following three overloads of the IndexOf method to find the index of a string in a string array:. IndexOf(Array, Object), to determine the first occurrence of the string "the" in a string array.
A streamlined version of your fill-in approach
In : arr = np.arange(10,22).reshape(2,3,2) In : res = np.zeros((arr.shape,arr.shape,4),arr.dtype) In : res[:,:,2:] = arr
The next step took a bit of trial and error. We fill in the indices with broadcasting. We need arrays that can broadcast to (2,3), the first 2 dimensions of
In : res[:,:,0] = np.arange(arr.shape) In : res[:,:,1] = np.arange(arr.shape)[:,None] # size 2 column In : res Out: array([[[ 0, 0, 10, 11], [ 1, 0, 12, 13], [ 2, 0, 14, 15]], [[ 0, 1, 16, 17], [ 1, 1, 18, 19], [ 2, 1, 20, 21]]])
4. NumPy Basics: Arrays and Vectorized Computation, If you're new to Python and just looking to get your hands dirty working with data Fast vectorized array operations for data munging and cleaning, subsetting and eye, identity, Create a square N x N identity matrix (1's on the diagonal and 0's In a two-dimensional array, the elements at each index are no longer scalars� SCALA: change the separator in Array arrays,string,scala,delimiter I have an Array like this. scala> var x=Array("a","x,y","b") x: Array[String] = Array(a, x,y, b) How do I change the separator comma in array to a :. And finally convert it to string like this.
9. Lists — How to Think Like a Computer Scientist: Learning with , A list is an ordered set of values, where each value is identified by an index. The values that make up a list are called its elements. With all these ways to create lists, it would be disappointing if we couldn't assign list values to variables Write a function add_vectors(u, v) that takes two lists of numbers of the same length,� NOTE: Copying array indices and elements isn’t expensive in terms of memory. Internally, gawk maintains reference counts to data. For example, when asort() copies the first array to the second one, there is only one copy of the original array elements’ data, even though both arrays use the values.
11. Lists — How to Think Like a Computer Scientist: Learning with , The values that make up a list are called its elements, or its items. Lists and strings — and other collections that maintain the order of their items — are Write a function add_vectors(u, v) that takes two lists of numbers of the same length, def swap(x, y): # Incorrect version print("before swap statement: x:", x, "y :", y) (x, y)� There are only four elements in the array that contains information, but the array is 51 elements long, with a highest index of 50. Adding and Removing Elements in Array Perl provides a number of useful functions to add and remove elements in an array.
Index exceeds number of array elements (1)?, Learn more about index-error. Index exceeds number of array elements (1)?. Follow how did u make the change? X(ii,:) = rand(1,Npar). den=sum(1./F); y = myfunc(x). plot(x,y). avg_y = y(1:length(x)-1) + diff(y)/2;. A = sum(diff(x). To find array elements that meet a condition, use find in conjunction with a relational expression. For example, find(X<5) returns the linear indices to the elements in X that are less than 5. To directly find the elements in X that satisfy the condition X<5, use X(X<5).
- Your proposed solution is very clear and was much easier to apply to other problems than the other proposed ones (Even though they also work great!). I will edit the accepted answer to this one. Thanks!
- Without an explanation, this answer even though works in this case, has no possibility for application to other problems. One liners are fashionable but without explanation lose their value. Perhaps you can add few words to your answer
- @Bazingaa Did you actually look at this one? I'd say it's pretty self explanatory, almost like plain Engish: "Concatenate indices for
mag_2D(with their leading axis moved to the end) with
...,doesn't look like plain English to me and I think even new comers. Of course you are English level C2 so to you it looks like self explanatory ;)
- @Bazingaa Alright, alright. I've added a few lines of explanation.