Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I want to print numpy arrays nicer, using the indices into the array [0 1] indexes row zero and column one:

Suppose we have a big numpy array

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

Now we want to print row 100, but only the last ten entries:

print x[100, -10:]

This should result in something like:

     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  

I produced this by getting the index as follows:

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]])

But this seems to be very inefficient, especially, when the indexing gets more complicated, or X gets bigger (As in billions of entries).

Is there a better way of creating index arrays from an index (here the index is [100, -10:] and the index array is index)?

share|improve this question
4  
I think this solution is very readable. If you want to use this only for printing purposes, speed is not going to be an issue in most circumstances. Premature optimization is evil. –  flebool May 14 at 13:31

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.