python - 如何根据条件从 NumPy 矩阵中获取行的子集?

标签 python numpy matrix

如何返回一组符合给定条件的 NumPy 矩阵行?

这是一个 Numpy 矩阵对象

>>> X

matrix([['sunny', 'hot', 'high', 'FALSE'],
        ['sunny', 'hot', 'high', 'TRUE'],
        ['overcast', 'hot', 'high', 'FALSE'],
        ['rainy', 'mild', 'high', 'FALSE'],
        ['rainy', 'cool', 'normal', 'FALSE'],
        ['rainy', 'cool', 'normal', 'TRUE'],
        ['overcast', 'cool', 'normal', 'TRUE'],
        ['sunny', 'mild', 'high', 'FALSE'],
        ['sunny', 'cool', 'normal', 'FALSE'],
        ['rainy', 'mild', 'normal', 'FALSE'],
        ['sunny', 'mild', 'normal', 'TRUE'],
        ['overcast', 'mild', 'high', 'TRUE'],
        ['overcast', 'hot', 'normal', 'FALSE'],
        ['rainy', 'mild', 'high', 'TRUE']], 
       dtype='|S8')

我想获取第一列值为 'rainy' 的所有行的集合,所以它尝试了这个

>>> X[X[:,0]=='rainy']

matrix([['rainy', 'rainy', 'rainy', 'rainy', 'rainy']], 
       dtype='|S8')

但我想要这样的输出

matrix([['rainy', 'mild', 'high', 'FALSE'],
        ['rainy', 'cool', 'normal', 'FALSE'],
        ['rainy', 'cool', 'normal', 'TRUE'],
        ['rainy', 'mild', 'normal', 'FALSE'],
        ['rainy', 'mild', 'high', 'TRUE']], 
       dtype='|S8')

应该怎么做?

最佳答案

>>> X[(X[:, 0] == 'rainy').ravel(), :]
matrix([['rainy', 'mild', 'high', 'FALSE'],
        ['rainy', 'cool', 'normal', 'FALSE'],
        ['rainy', 'cool', 'normal', 'TRUE'],
        ['rainy', 'mild', 'normal', 'FALSE'],
        ['rainy', 'mild', 'high', 'TRUE']], 
       dtype='|S8')

如果您查看比较结果:

>>> X[:, 0] == 'rainy'
array([[False],
       [False],
       [False],
       [ True],
       [ True],
       [ True],
       [False],
       [False],
       [False],
       [ True],
       [False],
       [False],
       [False],
       [ True]], dtype=bool)

需要使用 ravel 将其展平为向量:

(X[:, 0] == 'rainy').ravel()
array([False, False, False,  True,  True,  True, False, False, False,
        True, False, False, False,  True], dtype=bool)

对于额外的约束,这有效:

X[(X[:, 0] == 'rainy').ravel() & (X[:, 1] == 'cool').ravel(), :]
matrix([['rainy', 'cool', 'normal', 'FALSE'],
        ['rainy', 'cool', 'normal', 'TRUE']], 
       dtype='|S8')

关于python - 如何根据条件从 NumPy 矩阵中获取行的子集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36206287/

相关文章:

python - 如何每行打印出一个元组的元素

python - 什么时候 ndarray 的大小不固定?

c - 在邻接矩阵中随机添加 INFTY 值

python - 获取已排序矩阵的索引

python - 带有日期轴的 Pandas/matplotlib 图显示正确的日/月但错误的工作日/年

python - QFrame边框不显示

python - 如何在python中打印时间和日期

python - 使用 pytables 构造巨大的 numpy 数组

python - Numpy.dot 错误?不一致的 NaN 行为

python - 如何使用numpy获取没有对角线的三角形上矩阵