根据列值过滤numpy ndarray(矩阵)

Nic*_* M. 6 python numpy matrix

这个问题是关于NumPy ndarray根据一些列值过滤a .

我有一个相当大NumPy ndarray(300000,50),我根据某些特定列中的值过滤它.我有,ndtypes所以我可以按名称访问每一列.

第一列被命名为category_code和我需要过滤矩阵只返回中行category_code("A", "B", "C").

结果将需要是另一个名称NumPy ndarray仍可访问其列的列dtype.

这是我现在所做的:

index = numpy.asarray([row['category_code'] in ('A', 'B', 'C') for row in data])
filtered_data = data[index]
Run Code Online (Sandbox Code Playgroud)

列表理解如:

list = [row for row in data if row['category_code'] in ('A', 'B', 'C')]
filtered_data = numpy.asarray(list)
Run Code Online (Sandbox Code Playgroud)

不行,因为dtypes我原来不再可以访问.

是否有更好/更多的Pythonic方法来实现相同的结果?

可能看起来像的东西:

filtered_data = data.where({'category_code': ('A', 'B','C'})
Run Code Online (Sandbox Code Playgroud)

谢谢!

dou*_*oug 10

您可以使用基于NumPy的库Pandas,它具有更常用的ndarrays实现:

>>> # import the library
>>> import pandas as PD
Run Code Online (Sandbox Code Playgroud)

创建一些示例数据作为python字典,其是列名,其是作为python列表的列值; 每列一个键/值对

>>> data = {'category_code': ['D', 'A', 'B', 'C', 'D', 'A', 'C', 'A'], 
            'value':[4, 2, 6, 3, 8, 4, 3, 9]}

>>> # convert to a Pandas 'DataFrame'
>>> D = PD.DataFrame(data)
Run Code Online (Sandbox Code Playgroud)

要仅返回category_code为B或C的行,从概念上讲两个步骤,但可以在一行中轻松完成:

>>> # step 1: create the index 
>>> idx = (D.category_code== 'B') | (D.category_code == 'C')

>>> # then filter the data against that index:
>>> D.ix[idx]

        category_code  value
   2             B      6
   3             C      3
   6             C      3
Run Code Online (Sandbox Code Playgroud)

请注意PandasNumPy索引之间的区别,NumPy是构建Pandas的库.在NumPy中,您只需将索引放在括号内,指示使用","索引哪个维度,并使用":"表示您希望其他维度中的所有值(列):

>>>  D[idx,:]
Run Code Online (Sandbox Code Playgroud)

在Pandas中,您调用数据框的ix方法,并将索引放在括号内:

>>> D.loc[idx]
Run Code Online (Sandbox Code Playgroud)