【问题标题】:Filter numpy ndarray (matrix) according to column values根据列值过滤numpy ndarray(矩阵)
【发布时间】:2012-08-23 20:25:58
【问题描述】:

这个问题是关于根据某些列值过滤NumPyndarray

我有一个相当大的 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]

列表理解如下:

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

无法使用,因为我原来拥有的 dtypes 已无法访问。

有没有更好/更 Pythonic 的方式来实现相同的结果?

可能看起来像的东西:

filtered_data = data.where({'category_code': ('A', 'B','C'})

谢谢!

【问题讨论】:

  • 大概你的意思是row['category_code'] 而不是index = 行中的data['category_code']
  • 杜格尔,你是对的。我修好了它。谢谢!
  • 我真的不认为您需要改进现有解决方案,您 (i) 构建满足您条件的行的 bool 数组和 (ii) 使用此数组来索引您的数据。它干净、可读、高效……你还想要什么?
  • Pierre GM- 这个例子是一个简化的例子。我实际上希望能够将其概括为多个列值(例如 category_code 是在这些值中,col_2 在该范围内,col_3 不大于 X,并且...)

标签: python matrix numpy


【解决方案1】:

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

>>> # import the library
>>> import pandas as PD

创建一些示例 data 作为 python 字典,其 keys 是列名,其 values 是列值作为 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)

要仅返回 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

注意 PandasNumPy 中的索引之间的区别,NumPy 是构建 Pandas 的库。在 NumPy 中,您只需将索引放在括号内,用“,”指示您要索引的维度,并使用“:”表示您想要另一个维度中的所有值(列):

>>>  D[idx,:]

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

>>> D.loc[idx]

【讨论】:

  • D.ix[idx] 现在已弃用 (as of 0.20.0),因此您可以在最后一行中使用 D.loc[idx]
【解决方案2】:

如果可以选择,我强烈推荐pandas:它具有"column indexing" built-in 以及许多其他功能。它建立在 numpy 之上。

【讨论】:

  • 看起来非常棒。要试一试。我将其用作 scikit-learn 库的输入。看起来熊猫还有助于从 csv 读取数据并处理丢失的数据。我想我白白地重新实现了一堆:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-08
  • 2021-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-20
相关资源
最近更新 更多