Array printing function
$Id: arrayprint.py,v 1.9 2005/09/13 13:58:44 teoliphant Exp $
Class | _TimelikeFormat |
Undocumented |
Class | BoolFormat |
Undocumented |
Class | ComplexFloatingFormat |
Formatter for subtypes of np.complexfloating |
Class | DatetimeFormat |
Undocumented |
Class | FloatingFormat |
Formatter for subtypes of np.floating |
Class | IntegerFormat |
Undocumented |
Class | StructuredVoidFormat |
Formatter for structured np.void objects. |
Class | SubArrayFormat |
Undocumented |
Class | TimedeltaFormat |
Undocumented |
Function | _array2string |
Undocumented |
Function | _array2string_dispatcher |
Undocumented |
Function | _array_repr_dispatcher |
Undocumented |
Function | _array_repr_implementation |
Internal version of array_repr() that allows overriding array2string. |
Function | _array_str_dispatcher |
Undocumented |
Function | _array_str_implementation |
Internal version of array_str() that allows overriding array2string. |
Function | _extendLine |
Undocumented |
Function | _extendLine_pretty |
Extends line with nicely formatted (possibly multi-line) string word. |
Function | _formatArray |
formatArray is designed for two modes of operation: |
Function | _get_format_function |
find the right formatting function for the dtype_ |
Function | _get_formatdict |
Undocumented |
Function | _get_legacy_print_mode |
Return the legacy print mode as an int. |
Function | _guarded_repr_or_str |
Undocumented |
Function | _leading_trailing |
Keep only the N-D corners (leading and trailing edges) of an array. |
Function | _make_options_dict |
Make a dictionary out of the non-None arguments, plus conversion of legacy and sanity checks. |
Function | _none_or_positive_arg |
Undocumented |
Function | _object_format |
Object arrays containing lists should be printed unambiguously |
Function | _recursive_guard |
Like the python 3.2 reprlib.recursive_repr, but forwards *args and **kwargs |
Function | _void_scalar_repr |
Implements the repr for structured-void scalars. It is called from the scalartypes.c.src code, and is placed here because it uses the elementwise formatters defined above. |
Function | array2string |
Return a string representation of an array. |
Function | array_repr |
Return the string representation of an array. |
Function | array_str |
Return a string representation of the data in an array. |
Function | dtype_is_implied |
Determine if the given dtype is implied by the representation of its values. |
Function | dtype_short_repr |
Convert a dtype to a short form which evaluates to the same dtype. |
Function | format_float_positional |
Format a floating-point scalar as a decimal string in positional notation. |
Function | format_float_scientific |
Format a floating-point scalar as a decimal string in scientific notation. |
Function | get_printoptions |
Return the current print options. |
Function | printoptions |
Context manager for setting print options. |
Function | repr_format |
Undocumented |
Function | set_printoptions |
Set printing options. |
Function | set_string_function |
Set a Python function to be used when pretty printing arrays. |
Function | str_format |
Undocumented |
Variable | _array2string_impl |
Undocumented |
Variable | _default_array_repr |
Undocumented |
Variable | _default_array_str |
Undocumented |
Variable | _format_options |
Undocumented |
Variable | _typelessdata |
Undocumented |
Undocumented
Undocumented
Undocumented
formatArray is designed for two modes of operation:
Undocumented
Keep only the N-D corners (leading and trailing edges) of an array.
Should be passed a base-class ndarray, since it makes no guarantees about preserving subclasses.
Return a string representation of an array.
max_line_width
.
Defaults to numpy.get_printoptions()['linewidth'].prefix : str, optional suffix : str, optional
The length of the prefix and suffix strings are used to respectively align and wrap the output. An array is typically printed as:
prefix + array2string(a) + suffixThe output is left-padded by the length of the prefix string, and wrapping is forced at the column max_line_width - len(suffix). It should be noted that the content of prefix and suffix strings are not included in the output.
Has no effect, do not use.
If not None, the keys should indicate the type(s) that the respective formatting function applies to. Callables should return a string. Types that are not specified (by their corresponding keys) are handled by the default formatters. Individual types for which a formatter can be set are:
numpy.timedelta64
numpy.datetime64
numpy.void
numpy.string_
and numpy.unicode_
Other keys that can be used to set a group of types at once are:
Controls the interpretation of the precision
option for
floating-point types.
Defaults to numpy.get_printoptions()['floatmode'].
Can take the following values:
precision
fractional digits,
even if this would print more or fewer digits than
necessary to specify the value uniquely.precision
option is ignored.precision
fractional digits, but if
an element can be uniquely represented with fewer digits
only print it with that many.precision
fractional digits,
but if every element in the array can be uniquely
represented with an equal number of fewer digits, use that
many digits for all elements.False
, optionalIf set to the string '1.13'
enables 1.13 legacy printing mode. This
approximates numpy 1.13 print output by including a space in the sign
position of floats and different behavior for 0d arrays. If set to
False
, disables legacy mode. Unrecognized strings will be ignored
with a warning for forward compatibility.
formatter
does not return a string.array_str, array_repr, set_printoptions, get_printoptions
If a formatter is specified for a certain type, the precision
keyword is
ignored for that type.
This is a very flexible function; array_repr
and array_str
are using
array2string
internally so keywords with the same name should work
identically in all three functions.
>>> x = np.array([1e-16,1,2,3]) >>> np.array2string(x, precision=2, separator=',', ... suppress_small=True) '[0.,1.,2.,3.]'
>>> x = np.arange(3.) >>> np.array2string(x, formatter={'float_kind':lambda x: "%.2f" % x}) '[0.00 1.00 2.00]'
>>> x = np.arange(3) >>> np.array2string(x, formatter={'int':lambda x: hex(x)}) '[0x0 0x1 0x2]'
Return the string representation of an array.
max_line_width
.
Defaults to numpy.get_printoptions()['linewidth'].array_str, array2string, set_printoptions
>>> np.array_repr(np.array([1,2])) 'array([1, 2])' >>> np.array_repr(np.ma.array([0.])) 'MaskedArray([0.])' >>> np.array_repr(np.array([], np.int32)) 'array([], dtype=int32)'
>>> x = np.array([1e-6, 4e-7, 2, 3]) >>> np.array_repr(x, precision=6, suppress_small=True) 'array([0.000001, 0. , 2. , 3. ])'
Return a string representation of the data in an array.
The data in the array is returned as a single string. This function is
similar to array_repr
, the difference being that array_repr
also
returns information on the kind of array and its data type.
max_line_width
.
Defaults to numpy.get_printoptions()['linewidth'].array2string, array_repr, set_printoptions
>>> np.array_str(np.arange(3)) '[0 1 2]'
Determine if the given dtype is implied by the representation of its values.
>>> np.core.arrayprint.dtype_is_implied(int) True >>> np.array([1, 2, 3], int) array([1, 2, 3]) >>> np.core.arrayprint.dtype_is_implied(np.int8) False >>> np.array([1, 2, 3], np.int8) array([1, 2, 3], dtype=int8)
Convert a dtype to a short form which evaluates to the same dtype.
The intent is roughly that the following holds
>>> from numpy import * >>> dt = np.int64([1, 2]).dtype >>> assert eval(dtype_short_repr(dt)) == dt
Format a floating-point scalar as a decimal string in positional notation.
Provides control over rounding, trimming and padding. Uses and assumes IEEE unbiased rounding. Uses the "Dragon4" algorithm.
unique
is
True
, but must be an integer if unique is False
.True
, use a digit-generation strategy which gives the shortest
representation which uniquely identifies the floating-point number from
other values of the same type, by judicious rounding. If precision
is given fewer digits than necessary can be printed, or if min_digits
is given more can be printed, in which cases the last digit is rounded
with unbiased rounding.
If False
, digits are generated as if printing an infinite-precision
value and stopping after precision
digits, rounding the remaining
value with unbiased roundingTrue
, the cutoffs of precision
and min_digits
refer to the
total number of digits after the decimal point, including leading
zeros.
If False
, precision
and min_digits
refer to the total number of
significant digits, before or after the decimal point, ignoring leading
zeros.Controls post-processing trimming of trailing digits, as follows:
Minimum number of digits to print. Only has an effect if unique=True
in which case additional digits past those necessary to uniquely
identify the value may be printed, rounding the last additional digit.
-- versionadded:: 1.21.0
format_float_scientific
>>> np.format_float_positional(np.float32(np.pi)) '3.1415927' >>> np.format_float_positional(np.float16(np.pi)) '3.14' >>> np.format_float_positional(np.float16(0.3)) '0.3' >>> np.format_float_positional(np.float16(0.3), unique=False, precision=10) '0.3000488281'
Format a floating-point scalar as a decimal string in scientific notation.
Provides control over rounding, trimming and padding. Uses and assumes IEEE unbiased rounding. Uses the "Dragon4" algorithm.
unique
is
True
, but must be an integer if unique is False
.True
, use a digit-generation strategy which gives the shortest
representation which uniquely identifies the floating-point number from
other values of the same type, by judicious rounding. If precision
is given fewer digits than necessary can be printed. If min_digits
is given more can be printed, in which cases the last digit is rounded
with unbiased rounding.
If False
, digits are generated as if printing an infinite-precision
value and stopping after precision
digits, rounding the remaining
value with unbiased roundingControls post-processing trimming of trailing digits, as follows:
Minimum number of digits to print. This only has an effect for
unique=True
. In that case more digits than necessary to uniquely
identify the value may be printed and rounded unbiased.
-- versionadded:: 1.21.0
format_float_positional
>>> np.format_float_scientific(np.float32(np.pi)) '3.1415927e+00' >>> s = np.float32(1.23e24) >>> np.format_float_scientific(s, unique=False, precision=15) '1.230000071797338e+24' >>> np.format_float_scientific(s, exp_digits=4) '1.23e+0024'
Return the current print options.
Dictionary of current print options with keys
- precision : int
- threshold : int
- edgeitems : int
- linewidth : int
- suppress : bool
- nanstr : str
- infstr : str
- formatter : dict of callables
- sign : str
For a full description of these options, see set_printoptions
.
set_printoptions, printoptions, set_string_function
Context manager for setting print options.
Set print options for the scope of the with
block, and restore the old
options at the end. See set_printoptions
for the full description of
available options.
>>> from numpy.testing import assert_equal >>> with np.printoptions(precision=2): ... np.array([2.0]) / 3 array([0.67])
The as
-clause of the with
-statement gives the current print options:
>>> with np.printoptions(precision=2) as opts: ... assert_equal(opts, np.get_printoptions())
set_printoptions, get_printoptions
Set printing options.
These options determine the way floating point numbers, arrays and other NumPy objects are displayed.
floatmode
is not fixed
, to print as many digits as
necessary to uniquely specify the value.sys.maxsize
.If not None, the keys should indicate the type(s) that the respective formatting function applies to. Callables should return a string. Types that are not specified (by their corresponding keys) are handled by the default formatters. Individual types for which a formatter can be set are:
numpy.timedelta64
numpy.datetime64
numpy.string_
and numpy.unicode_
np.object_
arraysOther keys that can be used to set a group of types at once are:
Controls the interpretation of the precision
option for
floating-point types. Can take the following values
(default maxprec_equal):
precision
fractional digits,precision
option is ignored.precision
fractional digits, but ifprecision
fractional digits,False
, optionalIf set to the string '1.13'
enables 1.13 legacy printing mode. This
approximates numpy 1.13 print output by including a space in the sign
position of floats and different behavior for 0d arrays. This also
enables 1.21 legacy printing mode (described below).
If set to the string '1.21'
enables 1.21 legacy printing mode. This
approximates numpy 1.21 print output of complex structured dtypes
by not inserting spaces after commas that separate fields and after
colons.
If set to False
, disables legacy mode.
Unrecognized strings will be ignored with a warning for forward compatibility.
get_printoptions, printoptions, set_string_function, array2string
formatter
is always reset with a call to set_printoptions
.
Use printoptions
as a context manager to set the values temporarily.
Floating point precision can be set:
>>> np.set_printoptions(precision=4) >>> np.array([1.123456789]) [1.1235]
Long arrays can be summarised:
>>> np.set_printoptions(threshold=5) >>> np.arange(10) array([0, 1, 2, ..., 7, 8, 9])
Small results can be suppressed:
>>> eps = np.finfo(float).eps >>> x = np.arange(4.) >>> x**2 - (x + eps)**2 array([-4.9304e-32, -4.4409e-16, 0.0000e+00, 0.0000e+00]) >>> np.set_printoptions(suppress=True) >>> x**2 - (x + eps)**2 array([-0., -0., 0., 0.])
A custom formatter can be used to display array elements as desired:
>>> np.set_printoptions(formatter={'all':lambda x: 'int: '+str(-x)}) >>> x = np.arange(3) >>> x array([int: 0, int: -1, int: -2]) >>> np.set_printoptions() # formatter gets reset >>> x array([0, 1, 2])
To put back the default options, you can use:
>>> np.set_printoptions(edgeitems=3, infstr='inf', ... linewidth=75, nanstr='nan', precision=8, ... suppress=False, threshold=1000, formatter=None)
Also to temporarily override options, use printoptions
as a context manager:
>>> with np.printoptions(precision=2, suppress=True, threshold=5): ... np.linspace(0, 10, 10) array([ 0. , 1.11, 2.22, ..., 7.78, 8.89, 10. ])
Set a Python function to be used when pretty printing arrays.
set_printoptions, get_printoptions
>>> def pprint(arr): ... return 'HA! - What are you going to do now?' ... >>> np.set_string_function(pprint) >>> a = np.arange(10) >>> a HA! - What are you going to do now? >>> _ = a >>> # [0 1 2 3 4 5 6 7 8 9]
We can reset the function to the default:
>>> np.set_string_function(None) >>> a array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
repr
affects either pretty printing or normal string representation.
Note that __repr__ is still affected by setting __str__
because the width of each array element in the returned string becomes
equal to the length of the result of __str__().
>>> x = np.arange(4) >>> np.set_string_function(lambda x:'random', repr=False) >>> x.__str__() 'random' >>> x.__repr__() 'array([0, 1, 2, 3])'