-4

I'm a Matlab user and I'm learning Python. I want to create new arrays with element-wise comparison. Using Matlab: In the example I have solar radiation, temperature and relative humidity:

rad=[0,0,0,0,0,12,55,95,50,12,60,12,5,0,0,0];
rhu=[90,91,95,94,93,90,88,89,85,83,81,80,80,85,90,92];
tmp=[3,5,6,9,8,9,10,11,13,15,14,13,11,9,8,8];

Now I want to get a new array that contains the temperatures corresponding to solar radiation greater than 50 and relative humidity more than 87. I do:

tmp_rad=tmp(rad>50 & rhu>87)

In python if I type:

rad=np.array([0,0,0,0,0,12,55,95,50,12,60,12,5,0,0,0])
rhu=np.array([90,91,95,94,93,90,88,89,85,83,81,80,80,85,90,92])
tmp=np.array([3,5,6,9,8,9,10,11,13,15,14,13,11,9,8,8])
tmp_rad=tmp[rad>50 and rhu>87]

I get the following error "ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()"

Thank you

UPDATE: Sorry I made a mistake: I knew how to treat this firt question but I totally forgot to add the second condition. The problem comes when I want to have two or more comparisons.

scana
  • 111
  • 1
  • 11
  • 6
    It's just `tmp[rad>=50]`, which square brackets instead of parens. This should be covered very early in any tutorial on numpy. – abarnert Apr 18 '18 at 17:24

2 Answers2

2

This is almost the same in numpy as in Matlab:

rad=np.array([0,0,0,0,0,12,55,95,50,12,60,12,5,0,0,0])
tmp=np.array([3,5,6,9,8,9,10,11,13,15,14,13,11,9,8,8])
tmp_rad=tmp[rad>=50]

The rad>=50 means exactly what you'd expect. All basic operations—arithmetic, comparisons, etc.—are elementwise, as explained in the Basic Operations section of the quickstart tutorial. So this returns an array of booleans, where each element is either True or False depending on whether the corresponding element of rad is >=50 or not.

Python does array indexing with square brackets, as explained in the Indexing, Slicing and Iterating section of the quickstart tutorial. So numpy also uses square brackets for selecting with a boolean array, as explained in the Indexing with Boolean Arrays section of the quickstart tutorial.

abarnert
  • 354,177
  • 51
  • 601
  • 671
  • @LuisMendo They all work for me. I've seen the scipy site go down briefly in the past, so maybe that's what happened to you; can you try again? – abarnert Apr 19 '18 at 17:54
1

Finally I found it here: Numpy array, how to select indices satisfying multiple conditions?

I had to replace "and" with "&" and add brackets:

tmp_rad=tmp[(rad>50)&(rhu>87)]
scana
  • 111
  • 1
  • 11