如何根据numpy中的条件拆分数组? [英] How to split an array according to a condition in numpy?
本文介绍了如何根据numpy中的条件拆分数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,我有一个ndarray
:
a = np.array([1, 3, 5, 7, 2, 4, 6, 8])
现在我想将a
分为两部分,一个是所有数字< 5,另一个是所有> = 5:
Now I want to split a
into two parts, one is all numbers <5 and the other is all >=5:
[array([1,3,2,4]), array([5,7,6,8])]
当然,我可以遍历a
并创建两个新数组.但是我想知道numpy是否提供了一些更好的方法?
Certainly I can traverse a
and create two new array. But I want to know does numpy provide some better ways?
类似地,对于多维数组,例如
Similarly, for multidimensional array, e.g.
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[2, 4, 7]])
我想根据第一列< 3和> = 3对其进行拆分,结果是:
I want to split it according to the first column <3 and >=3, which result is:
[array([[1, 2, 3],
[2, 4, 7]]),
array([[4, 5, 6],
[7, 8, 9]])]
有没有更好的方法来遍历它?谢谢.
Are there any better ways instead of traverse it? Thanks.
推荐答案
import numpy as np
def split(arr, cond):
return [arr[cond], arr[~cond]]
a = np.array([1,3,5,7,2,4,6,8])
print split(a, a<5)
a = np.array([[1,2,3],[4,5,6],[7,8,9],[2,4,7]])
print split(a, a[:,0]<3)
这将产生以下输出:
[array([1, 3, 2, 4]), array([5, 7, 6, 8])]
[array([[1, 2, 3],
[2, 4, 7]]), array([[4, 5, 6],
[7, 8, 9]])]
这篇关于如何根据numpy中的条件拆分数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文