Skip to main content
 首页 » 编程设计

python之Numpy 索引到索引数组

2024年11月01日9jyk

我想更好地打印 numpy 数组,使用数组 [0 1] 索引行零和第一列中的索引:

假设我们有一个大的 numpy 数组

x = np.arange(400*8000).reshape(400,8000).astype(float) 

现在我们要打印第 100 行,但只打印最后十个条目:

print x[100, -10:] 

结果应该是这样的:

     Index     |    X      
  [ 100 7990]  |  807990   
  [ 100 7991]  |  807991   
  [ 100 7992]  |  807992   
  [ 100 7993]  |  807993   
  [ 100 7994]  |  807994   
  [ 100 7995]  |  807995   
  [ 100 7996]  |  807996   
  [ 100 7997]  |  807997   
  [ 100 7998]  |  807998   
  [ 100 7999]  |  807999   

我通过如下获取索引生成了这个:

index = np.indices(X.shape)[:, 100, -10:] 
print index 
# array([[ 100,  100,  100,  100,  100,  100,  100,  100,  100,  100], 
#        [7990, 7991, 7992, 7993, 7994, 7995, 7996, 7997, 7998, 7999]]) 

但这似乎非常低效,尤其是当索引变得更加复杂,或者 X 变得更大(如数十亿条目)时。

有没有更好的方法从索引创建索引数组(这里的索引是[100, -10:],索引数组是index)?

请您参考如下方法:

创建索引数组只是一个数学问题。为此,您不需要棘手的内置函数。例如,下面的函数应该很适合您,并且可以立即运行。

def getIndices(x, row, lastNCols): 
    """ 
    x = your matrix 
    row = the index of the row you want (100 in your case) 
    lastNCols = the number of columns you want to grab off the end of that  
                row (10 in your case) 
    """ 
    rows = np.full(lastNCols, row, dtype=int32) 
    cols = np.arange(x.shape[1] - lastNCols, x.shape[1], dtype=int32) 
    return np.column_stack((rows, cols)).T 

运行:

x = np.arange(400*8000).reshape(400,8000).astype(float) 
getIndices(x, 100, 10) 

输出:

array([[ 100,  100,  100,  100,  100,  100,  100,  100,  100,  100], 
       [7990, 7991, 7992, 7993, 7994, 7995, 7996, 7997, 7998, 7999]])