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

标签 python matrix numpy

这道题是关于根据某些列值过滤NumPy ndarray

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

谢谢!

最佳答案

您可以使用基于NumPy 的库,Pandas ,它有一个更通用的 ndarrays 实现:

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

创建一些示例数据作为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)

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

关于python - 根据列值过滤numpy ndarray(矩阵),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12099433/

相关文章:

python - 使用 Pandas 重新采样移位间隔

python - Python中将json转换为coo稀疏矩阵

python获取扩展文件: splitext vs endswith

Python - os.system - 输入具有多个文件路径的命令行(r"C :\etc") 的替代品

c++ - Windows Python C 扩展仅适用于我自己的 Python 构建(使用 VC++ 2008 Express 的 32 位构建)

Python:为图形插值矩阵

c - 查找稀疏矩阵中元素周围的最大区域

python - 使用 Selenium 和 python 为 Instagram 提供上传文件路径

c++ - 返回二维 vector

python-3.x - 如何在没有默认 "sort"的情况下加入两个集合