Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
501 views
in Technique[技术] by (71.8m points)

python - How to find min and max values in a 3d array in numpy, and group the results?

I have a 3D NumPy array like so:

[[[4 1 5 2 5 5 7 8 9 7]
  [7 4 2 4 7 8 4 1 3 5]
  [6 1 2 1 1 1 2 3 7 6]
  [5 5 5 0 5 4 3 8 7 1]
  [2 8 6 7 4 7 5 5 5 1]]

 [[9 9 5 8 0 7 3 9 8 1]
  [9 1 9 5 7 4 5 4 7 0]
  [1 0 4 8 7 3 4 3 8 8]
  [8 1 3 1 7 0 9 9 3 8]
  [4 0 2 3 8 2 0 1 2 4]]

 [[1 6 2 4 4 0 2 3 0 3]
  [9 6 8 6 6 5 6 9 4 1]
  [0 4 0 2 9 1 1 2 4 6]
  [6 1 9 9 7 8 9 7 6 8]
  [9 3 9 0 7 0 0 0 7 0]]]

With it, I like to create a 2d ndarray like so:

[[6]
 [9]
 [9]]

Where each element of this 2d array is the max value of the third column on the original array:

enter image description here

I have been a couple of hours trying to puzzle this out but no luck...

I'm asking for a 2d array as the output because I have other calculations to make (say, I also need to min value of the second column in a similar fashion), but I think I can extrapolate those from this.

Any pointers are greatly appreciated!

question from:https://stackoverflow.com/questions/65648289/how-to-find-min-and-max-values-in-a-3d-array-in-numpy-and-group-the-results

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Have you tried this:

import numpy as np
x = np.random.randint(0, 10, (3, 5, 10))
print(x)
maxes = x[:,:,2].max(axis=1)
print(maxes)

[[[5 0 6 6 4 7 5 0 4 8]
  [0 6 8 8 2 1 7 5 4 3]
  [2 7 5 5 0 2 6 8 6 3]
  [5 9 7 5 1 1 5 4 8 7]
  [0 2 3 7 8 1 9 1 2 6]]

 [[8 9 4 3 3 6 0 4 9 1]
  [1 5 6 4 3 2 7 7 0 2]
  [3 2 0 1 9 6 5 8 0 5]
  [6 1 5 9 1 6 4 7 4 5]
  [7 2 5 8 6 8 5 1 9 5]]

 [[9 4 0 9 0 6 3 7 4 1]
  [4 1 4 9 1 1 1 2 0 6]
  [7 3 3 2 5 2 0 6 9 1]
  [1 7 0 1 8 1 3 8 6 4]
  [6 9 0 2 6 0 2 1 7 7]]]
[8 6 4]

To understand how this works checkout:

And, to get the maximum of all the columns:

col_maximums = x.max(axis=1)
print(col_maximums)
                                                                                    
[[5 9 8 8 8 7 9 8 8 8]
 [8 9 6 9 9 8 7 8 9 5]
 [9 9 4 9 8 6 3 8 9 7]]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...