1

In Python, for an array how can I find the columns that at least contain one negative element? Additionally, how can I find the median of rows that include at least one negative value? Let's say that this is our array:

import numpy as np
a = np.array([[1,2,0,-4],[-3,4,-4,1],[3,6,2,9]])

Thanks in advance.

1 Answers1

4
>>> (a < 0).any(axis=0)
array([ True, False,  True,  True])

# Columns.
>>> np.median(a[:, (a < 0).any(axis=0)], axis=0)
array([1., 0., 1.])

# Rows.
>>> np.median(a[:, (a < 0).any(axis=0)], axis==1)
array([ 0., -3.,  3.])

# Median of rows where row contains at least one negative value.
>>> np.median(a[(a < 0).any(axis=1), :], axis=1)
array([ 0.5, -1. ])
Alexander
  • 105,104
  • 32
  • 201
  • 196
  • I think OP is doing a homework. Is it wise to show him the shortcut or the old-school way of doing it? – christopher de jesus Jan 14 '20 at 21:34
  • `a[:, bool_filter]`: The `:` means select all rows from `a`, and `bool_filter` is an array of boolean values indicating which columns to select. In this case, `(a < 0).any(axis=0)` which means `True` for any column (`axis=0`) that contains a negative value, otherwise `False`. – Alexander Jan 14 '20 at 21:48
  • Additionally, normally axis=0 means rows and axis=1 means columns. Here why it is opposite? –  Jan 14 '20 at 21:56
  • https://stackoverflow.com/questions/17079279/how-is-axis-indexed-in-numpys-array or https://docs.scipy.org/doc/numpy-1.13.0/glossary.html – Alexander Jan 14 '20 at 22:09