我有一个 2D numpy 数组,有 4 列和很多行(>10000,这个数字不固定)。
我需要创建n按其中一列的值划分子数组;我发现的最接近的问题是如何按列值对 Numpy 数组进行切片 https://stackoverflow.com/questions/7577443/how-slice-numpy-array-by-column-value;尽管如此,我不知道该字段中的确切值(它们是浮点数,并且在我需要的每个文件中都会更改),但我知道它们不超过 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
这将选择第三列值为 (50, 50.2] 的行。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)