cat cat - 5 months ago 15
Python Question

filter by array numpy

I am trying to filter my ndarray by another array I have collected (with the same values)

My main ndarray looks like

[['Name' 'Col1' 'Count']
['test' '' '413']
['erd' ' ' '60']
...,
['Td1' 'f' '904']
['Td2' 'K' '953']
['Td3' 'r' '111']]


I have another list with various matching names

names = ['Td1','test','erd']


What I'd Like to Do

I'd like to use the list names as a filter against the ndarray above?

What I've Tried

name_filter = main_ndarray[:,0] == names


This does not work

What I'd Expect

[['Name' 'Col1' 'Count']
['test' '' '413']
['erd' ' ' '60']
['Td1' 'f' '904']]

YXD YXD
Answer

Consider using Pandas for this kind of data:

import pandas as pd

data = [['Name', 'Col1', 'Count'],
        ['test', '', '413'],
        ['erd', ' ', '60'],
        ['Td1', 'f', '904'],
        ['Td2', 'K', '953'],
        ['Td3', 'r', '111']]

df = pd.DataFrame(data[1:], columns=data[0])
names = ['Td1','test','erd']
result = df[df.Name.isin(names)]

Results:

>>> df
   Name Col1 Count
0  test        413
1   erd         60
2   Td1    f   904
3   Td2    K   953
4   Td3    r   111
>>> result
   Name Col1 Count
0  test        413
1   erd         60
2   Td1    f   904
>>>

References