我有一个 2D numpy 数组,有 4 列和很多行(>10000,这个数字不固定)。
我需要根据其中一列的值创建 n 个子数组;我发现的最接近的问题是 How slice Numpy array by column value ;尽管如此,我不知道该字段中的确切值(它们是 float ,并且在我需要的每个文件中都会发生变化),但我知道它们不超过 20。
我想我可以逐行读取,记录不同的值,然后进行拆分,但我认为有一种更有效的方法可以做到这一点。
谢谢。
最佳答案
可以方便的使用多维切片:
import numpy as np
# just creating a random 2d array.
a = (np.random.random((10, 5)) * 100).astype(int)
print a
print
# select by the values of the 3rd column, selecting out more than 50.
b = a[a[:, 2] > 50]
# showing the rows for which the 3rd column value is > 50.
print b
另一个例子,更接近你在评论中的要求(?):
import numpy as np
# just creating a random 2d array.
a = np.random.random((10000, 5)) * 100
print a
print
# select by the values of the 3rd column, selecting out more than 50.
b = a[a[:, 2] > 50.0]
b = b[b[:, 2] <= 50.2]
# showing the rows for which the 3rd column value is > 50.
print b
这会选择第 3 列值为 (50, 50.2) 的行。
关于arrays - 如何根据第 i 个字段的值对 numpy 数组进行切片?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12290844/