0

I have a multidimensional numpy array like this:

print(original_array.shape) -> (3, 4, 3)

It contains values for a 3D grid in cartesian coordinates (x, y, z) I want to extract and append to a new array. Every point in the grid holds a value. So in the example above I have 3 * 4 * 3 = 36 values in total. Now the problem is that I have a huge array and using 3 loops and normal python lists is pretty slow. I bet there is a way more efficient solution using some numpy tricks. Any good ideas?

My working solution using for-loops:

new_array = []
for z in range(3):
    for y in range(4):
        for x in range(3):
            new_array.append([original_array[x][y][z][0]])  # this gets the value of every 3D point

I would like to structure the extracted data in a line by line fashion like this:

"""
x1      y1      z1          val1
x2      y1      z1          val2
x3      y1      z1          val3
x1      y2      z1          val4
x2      y2      z1          val5
x3      y2      z1          val6
x1      y3      z1          val7
x2      y3      z1          val8
x3      y3      z1          val9
x1      y4      z1          val10
x2      y4      z1          val11
x3      y4      z1          val12     
x1      y1      z2          val13
x2      y1      z2          val14
x3      y1      z2          val15   
. . . 
"""

2 Answers 2

1

What about

new_array = []
new_array.extend(np.ravel(old_array[:, :, :, 0]))
Sign up to request clarification or add additional context in comments.

3 Comments

Why are you keeping the extend step?
I thought a list was expected
How about np.ravel(old_array...).tolist()?
0

What you want to create is an array with:

  • indices of the source element in leftmost columns,
  • value of this element in another column,

and as I assume, it should be a Numpy array.

To do it, run just the following one-liner:

result = np.array([ list(idx) + [j] for idx, j in np.ndenumerate(original_array) ])

Comments

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.