2

I am trying to compare a 1D array element-wise to a 2D array, and returns the elements of the 2D array which fulfils the condition in a 2D array form without using a for loop. Preferably using numpy or quicker method.

a = range(1,10)
Tna = np.random.choice(a, size=[250,10,1000], replace=True)
sum_Ta = np.sum(Tna, axis = 1)
percent = np.percentile(sum_Ta, 5, axis =0)

Now I would like to get a 2D array which contains the elements of sum_Ta if the elements are smaller the percent. Such that 250 elements of sum_Ta are comparing with 1 element of percent for 1000 times. Originally I can do, ES = sum_Ta[sum_Ta < percent[:,None]], but it only gives me a 1D array, not a 2D array.

  • `range(1, 0)` returns an empty set, and `range(0,1)` will always return 0; do you mean `range(0, 2)`? Also, are you looking for the results to be a masking of the 2d array? Or a list of the matching elements? – Hal Jarrett Feb 26 '18 at 22:55

1 Answers1

2

Assuming you mean that for each row, you want the element of the row to be included if it is less than the percentage associated with its column.

Try the following:

mask = sum_Ta < (percent * np.ones((250,1)))
ES = np.zeros((250, 1000))
ES[mask] = sum_Ta[mask]
Hal Jarrett
  • 825
  • 9
  • 19
  • Sorry, I made a mistake. Should be a = range(0,10). The mask returns, "operands could not be broadcast together with shapes (1000,) (250,10) "? – Kingvader Wong Feb 26 '18 at 23:16
  • 1
    There was a typo in that first line, meant to be `np.ones((250, 1))`. See if that gives you the behavior you are looking for. – Hal Jarrett Feb 27 '18 at 14:20
  • 1
    The `percent * np.ones((250, 1))` line basically stretches the 1D array into columns, so that it can be compared element-wise with the 2D array – Hal Jarrett Feb 27 '18 at 14:21