3

I'm trying to create a numpy array of coordinates. Up until now, I've been just using x_coords, y_coords = numpy.indices((shape)). Now, however, I want to combine x_coords and y_coords into one array, such that x_coords = thisArray[:,:,0] and y_coords = thisArray[:,:,1] In this case, thisArray is a two-dimensional array. Is there a simple or pythonic way to do this?

I originally thought about using numpy.outer, but that doesn't quite give me what I need. A possible idea is just using concatenation of the indices array along the (2nd?) axis, but that doesn't seem like a very elegant solution. (it may be the cleanest one here though).

Thanks!

1 Answer 1

2

What np.indices returns is already an array, but x_coords = thisArray[0, :, :] and y_coords = thisArray[1, :, :]. Unless you have very strict requirements for your array of coordinates (namely that it be contiguous), you can take a view of that array with the first axis rolled to the end:

thisArray = numpy.rollaxis(numpy.indices(shape), 0, len(shape)+1)
Sign up to request clarification or add additional context in comments.

4 Comments

Hm, that seems to work -- what do you mean though by the condition that it be contiguous. (Are you talking about its location in memory?)
When you roll the axis, the memory layout of the data is not changed, only the strides of the array. In memory, all the x coordinates will be together at the beginning of the memory section, followed by all the y coordinates. If you created your array directly with the shape you are after, x and y coordinates would be alternating in memory. For some fancy stuff, the actual memory layout may slow certain computations, or require a copy of the array, which is slow. For instance, you cannot feed a non-contiguous array to np.frombuffer. But for most applications it is not an issue at all.
Hm okay, thanks. One more question then. Suppose I wanted to flatten the 2nd and third axis. (Because I don't really care what order they are in. I pretty much just want an array of vectors). How could I go about doing that?
You could reshape your array after rolling the axis. If the shape is (rows, cols, 2) simply do thisArray = thisArray.reshape(rows, cols*2), or the equivalent thisArray = thisArray.reshape(rows, -1). Because of your array not being contiguous, this reshaping cannot be done without copying the array. Shouldn't be an issue unless your array is huge.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.