Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter columns in numpy ndarray

I have an array of booleans that says which columns of another array I should drop.

For example:

selections = [True, False, True]
data = [[ 1, 2, 3 ],
        [ 4, 5, 6 ]]

I would like to have the following one:

new_data = [[ 1, 3 ],
            [ 4, 6 ]

All arrays are numpy.array in Python 2.7.

like image 699
Daniil Okhlopkov Avatar asked Mar 04 '16 18:03

Daniil Okhlopkov


People also ask

How do I filter an element in a NumPy array?

In NumPy, you filter an array using a boolean index list. A boolean index list is a list of booleans corresponding to indexes in the array. If the value at an index is True that element is contained in the filtered array, if the value at that index is False that element is excluded from the filtered array.

Is Ndarray same as NumPy array?

numpy. array is just a convenience function to create an ndarray ; it is not a class itself. You can also create an array using numpy. ndarray , but it is not the recommended way.


1 Answers

Once you actually use numpy.arrays, it all works:

import numpy as np

selections = np.array([True, False, True])
data = np.array([[ 1, 2, 3 ],
        [ 4, 5, 6 ]])

>>> data[:, selections]
array([[1, 3],
       [4, 6]])
like image 135
Ami Tavory Avatar answered Oct 12 '22 00:10

Ami Tavory