![](/img/trans.png)
[英]Pythonicaly get a subset of rows from a numpy matrix based on a condition on each row and all columns
[英]How to get a subset of rows from a NumPy Matrix based on a condition?
如何返回与给定条件匹配的NumPy矩阵的行集?
这是一个Numpy Matrix对象
>>> 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')
有多种方法可以做到这一点。
foo = np.where(X[:, 0] == 'rainy') # get the index
X[foo, :] # The result you want.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.