3

I often want to see the shape, dtype, and partial contents of a numpy array.

This can be done using:

print(x.shape, x.dtype, x)

However, if x is a long expression, this becomes awkward.

Is there perhaps an easy way to achieve this type of output using a built-in ndarray attribute or numpy function? (Obviously, one can create a custom function but I hope to avoid this.)

1
  • 1
    Not really. Sometimes I use x.__array_interface__ but that gives more than shape and dtype (and none of the values). Commented Aug 4, 2020 at 2:02

1 Answer 1

3

To prevent the possibly long output of the array you could (temporarily) set the threshold print option:

thresholdint, optional
Total number of array elements which trigger summarization rather than full repr (default 1000). To always use the full repr without summarization, pass sys.maxsize.

Example to set it temporarily using a context manager:

import numpy as np
x = np.arange(100)

with np.printoptions(threshold=5):
    print(x.shape, x.dtype, np.array_repr(x))
#(100,) int32 array([ 0,  1,  2, ..., 97, 98, 99])

(using np.array_repr(x) instead of simply x also shows you the type of array, i.e. array or MaskedArray)

You could also set your own string function:

def info(x):
    with np.printoptions(threshold=5):
        return f'{x.shape} {x.dtype} {np.array_repr(x)}'
        
np.set_string_function(info)

so that simply typing the variable name in the console returns your custom string representation:

In [1]: x
Out[1]: (100,) int32 array([ 0,  1,  2, ..., 97, 98, 99])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.