【问题标题】:How to acces rows in the ndarray with indices stored in the other array?如何使用存储在另一个数组中的索引访问数组中的行?
【发布时间】:2018-11-01 12:49:47
【问题描述】:

假设我有 1 个 1000x20 的二维数组:

X = np.random.randint(0,5001,size=(1000,20))

第二个包含 1000 个随机数的一维数组:

row_indices = np.random.permutation(X.shape[0])

我只想从 row_indices[0:600]、row_indices[600:800] 和 row_indices[800:1000] 访问 X 行。最好的方法是什么?

【问题讨论】:

  • y1 = X[row_indices[:600]]; y2 = X[row_indices[600:800]]; y3 = X[row_indices[800:]]?

标签: python python-3.x numpy multidimensional-array


【解决方案1】:

您可以将row_indices 的(切片)版本作为X 的下标传递以获取相应的行。

因此我们可以创建三个变量y1y2y3,它们各自获得X 的份额:

X = np.random.randint(0,5001,size=(1000,20))
row_indices = np.random.permutation(X.shape[0])

y1 = X[row_indices[0:600]]
y2 = X[row_indices[600:800]]
y3 = X[row_indices[800:1000]]

因此,y1 是一个 600×20 矩阵,其中包含来自 X 的行,前 600 个索引的索引为 row_indices,依此类推。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多