arrays - 如何根据第 i 个字段的值对 numpy 数组进行切片?

标签 arrays numpy split pandas

我有一个 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/

相关文章:

java - 显示未改变

python - 使用位掩码查找数据间隙

php - 将嵌套数组编码为没有数组索引的正确 json

javascript - 谷歌脚本错误: "Incorrect range width" when using setValues

python - 如何根据层次结构计算列值

r - 将数据框中的每个 x 个字符拆分为字符串

sql按空格将字符串拆分为postgresql中的表

r - 在数据框中按数字拆分列

python - cv2.error : OpenCV(4. 5.2) 👎 错误: (-5:Bad argument) 在函数 'cvtColor' 中

python - Pandas :一系列数组到一系列转置数组