jaycode - 9 months ago 31

Python Question

I have Xy:

`matrix([[1, 1, 1, 1],`

[1, 2, 2, 2],

[2, 3, 3, 3],

[2, 4, 4, 4]])

How do I return all rows with first column == 1?

Answer should be:

`matrix([[1, 1, 1, 1],`

[1, 2, 2, 2]])

Answer

The `matrix`

type should generally be avoided in favour of `numpy.array`

. However, if you feel you **need** to use it then you can filter a matrix using `numpy.compress`

.

When doing so, its important to flatten your filter ...

```
>>> numpy.compress((m[:,0] == 1).flat, m, axis=0)
matrix([[1, 1, 1, 1],
[1, 2, 2, 2]])
```

Here, `m[:,0] == 1`

returns a boolean matrix indicating which rows are considered acceptable. `numpy.compress`

will choose just those acceptable rows for us.