4

I have a NumPy array with a shape of (3,1,2):

A=np.array([[[1,4]],
            [[2,5]],
            [[3,2]]]).

I'd like to get the min in each column.

In this case, they are 1 and 2. I tried to use np.amin but it returns an array and that is not what I wanted. Is there a way to do this in just one or two lines of python code without using loops?

mengmengxyz
  • 819
  • 5
  • 10
  • 12
  • Possible duplicate of [numpy max vs amax vs maximum](http://stackoverflow.com/questions/33569668/numpy-max-vs-amax-vs-maximum) – ivan_pozdeev Mar 11 '16 at 01:39

2 Answers2

9

You can specify axis as parameter to numpy.min function.

In [10]: A=np.array([[[1,4]],
                [[2,5]],
                [[3,6]]])

In [11]: np.min(A)
Out[11]: 1

In [12]: np.min(A, axis=0)
Out[12]: array([[1, 4]])

In [13]: np.min(A, axis=1)
Out[13]: 
array([[1, 4],
       [2, 5],
       [3, 6]])

In [14]: np.min(A, axis=2)
Out[14]: 
array([[1],
       [2],
       [3]])
Akavall
  • 82,592
  • 51
  • 207
  • 251
  • @mengmengxyz, I am not sure that I understand your question. `np.min(np.array([[[1,4]],[[2,5]],[[3,2]]]), axis=0)` produces: `array([[1, 2]])`, isn't that what you are looking for? – Akavall Mar 11 '16 at 02:36
  • That works.. Sorry for confusing you. I messed up my code while doing the testing. Thanks a lot – mengmengxyz Mar 11 '16 at 02:46
1

You need to specify the axes along which you need to find the minimum. In your case, it is along the first two dimensions. So:

>>> np.min(A, axis=(0, 1))
array([1, 2])
Shaan
  • 141
  • 7