Reputation: 3170
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.)
Upvotes: 3
Views: 2824
Reputation: 30579
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])
Upvotes: 3