我如何打印格式化的NumPy数组以类似于这样的方式:
x = 1.23456
print('%.3f' % x)
如果我想打印numpy。Ndarray的浮点数,它打印几个小数,通常是“科学”格式,即使对于低维数组也很难读取。然而,numpy。Ndarray显然必须被打印为字符串,即%s。有解决办法吗?
我如何打印格式化的NumPy数组以类似于这样的方式:
x = 1.23456
print('%.3f' % x)
如果我想打印numpy。Ndarray的浮点数,它打印几个小数,通常是“科学”格式,即使对于低维数组也很难读取。然而,numpy。Ndarray显然必须被打印为字符串,即%s。有解决办法吗?
当前回答
使用numpy。Set_printoptions设置输出的精度:
import numpy as np
x = np.random.random(10)
print(x)
# [ 0.07837821 0.48002108 0.41274116 0.82993414 0.77610352 0.1023732
# 0.51303098 0.4617183 0.33487207 0.71162095]
np.set_printoptions(precision=3)
print(x)
# [ 0.078 0.48 0.413 0.83 0.776 0.102 0.513 0.462 0.335 0.712]
suppress禁止对小数字使用科学计数法:
y = np.array([1.5e-10, 1.5, 1500])
print(y)
# [ 1.500e-10 1.500e+00 1.500e+03]
np.set_printoptions(suppress=True)
print(y)
# [ 0. 1.5 1500. ]
要在本地应用打印选项,使用NumPy 1.15.0或更高版本,可以使用NumPy。Printoptions上下文管理器。 例如,在with-suite precision=3和suppress=True中设置:
x = np.random.random(10)
with np.printoptions(precision=3, suppress=True):
print(x)
# [ 0.073 0.461 0.689 0.754 0.624 0.901 0.049 0.582 0.557 0.348]
但是在with-suite之外,打印选项回到默认设置:
print(x)
# [ 0.07334334 0.46132615 0.68935231 0.75379645 0.62424021 0.90115836
# 0.04879837 0.58207504 0.55694118 0.34768638]
如果您使用的是较早版本的NumPy,则可以创建上下文管理器 你自己。例如,
import numpy as np
import contextlib
@contextlib.contextmanager
def printoptions(*args, **kwargs):
original = np.get_printoptions()
np.set_printoptions(*args, **kwargs)
try:
yield
finally:
np.set_printoptions(**original)
x = np.random.random(10)
with printoptions(precision=3, suppress=True):
print(x)
# [ 0.073 0.461 0.689 0.754 0.624 0.901 0.049 0.582 0.557 0.348]
防止从浮点数的末尾删除零:
np。Set_printoptions现在有一个格式化器参数,允许您为每种类型指定一个格式化函数。
np.set_printoptions(formatter={'float': '{: 0.3f}'.format})
print(x)
的打印
[ 0.078 0.480 0.413 0.830 0.776 0.102 0.513 0.462 0.335 0.712]
而不是
[ 0.078 0.48 0.413 0.83 0.776 0.102 0.513 0.462 0.335 0.712]
其他回答
这是我用的,它很简单:
print(np.vectorize("%.2f".__mod__)(sparse))
我使用
def np_print(array,fmt="10.5f"):
print (array.size*("{:"+fmt+"}")).format(*array)
对多维数组进行修改并不难。
几年后,下面又有一个。但对于日常使用,我只是
np.set_printoptions( threshold=20, edgeitems=10, linewidth=140,
formatter = dict( float = lambda x: "%.3g" % x )) # float arrays %.3g
''' printf( "... %.3g ... %.1f ...", arg, arg ... ) for numpy arrays too
Example:
printf( """ x: %.3g A: %.1f s: %s B: %s """,
x, A, "str", B )
If `x` and `A` are numbers, this is like `"format" % (x, A, "str", B)` in python.
If they're numpy arrays, each element is printed in its own format:
`x`: e.g. [ 1.23 1.23e-6 ... ] 3 digits
`A`: [ [ 1 digit after the decimal point ... ] ... ]
with the current `np.set_printoptions()`. For example, with
np.set_printoptions( threshold=100, edgeitems=3, suppress=True )
only the edges of big `x` and `A` are printed.
`B` is printed as `str(B)`, for any `B` -- a number, a list, a numpy object ...
`printf()` tries to handle too few or too many arguments sensibly,
but this is iffy and subject to change.
How it works:
numpy has a function `np.array2string( A, "%.3g" )` (simplifying a bit).
`printf()` splits the format string, and for format / arg pairs
format: % d e f g
arg: try `np.asanyarray()`
--> %s np.array2string( arg, format )
Other formats and non-ndarray args are left alone, formatted as usual.
Notes:
`printf( ... end= file= )` are passed on to the python `print()` function.
Only formats `% [optional width . precision] d e f g` are implemented,
not `%(varname)format` .
%d truncates floats, e.g. 0.9 and -0.9 to 0; %.0f rounds, 0.9 to 1 .
%g is the same as %.6g, 6 digits.
%% is a single "%" character.
The function `sprintf()` returns a long string. For example,
title = sprintf( "%s m %g n %g X %.3g",
__file__, m, n, X )
print( title )
...
pl.title( title )
Module globals:
_fmt = "%.3g" # default for extra args
_squeeze = np.squeeze # (n,1) (1,n) -> (n,) print in 1 line not n
See also:
http://docs.scipy.org/doc/numpy/reference/generated/numpy.set_printoptions.html
http://docs.python.org/2.7/library/stdtypes.html#string-formatting
'''
# http://stackoverflow.com/questions/2891790/pretty-printing-of-numpy-array
#...............................................................................
from __future__ import division, print_function
import re
import numpy as np
__version__ = "2014-02-03 feb denis"
_splitformat = re.compile( r'''(
%
(?<! %% ) # not %%
-? [ \d . ]* # optional width.precision
\w
)''', re.X )
# ... %3.0f ... %g ... %-10s ...
# -> ['...' '%3.0f' '...' '%g' '...' '%-10s' '...']
# odd len, first or last may be ""
_fmt = "%.3g" # default for extra args
_squeeze = np.squeeze # (n,1) (1,n) -> (n,) print in 1 line not n
#...............................................................................
def printf( format, *args, **kwargs ):
print( sprintf( format, *args ), **kwargs ) # end= file=
printf.__doc__ = __doc__
def sprintf( format, *args ):
""" sprintf( "text %.3g text %4.1f ... %s ... ", numpy arrays or ... )
%[defg] array -> np.array2string( formatter= )
"""
args = list(args)
if not isinstance( format, basestring ):
args = [format] + args
format = ""
tf = _splitformat.split( format ) # [ text %e text %f ... ]
nfmt = len(tf) // 2
nargs = len(args)
if nargs < nfmt:
args += (nfmt - nargs) * ["?arg?"]
elif nargs > nfmt:
tf += (nargs - nfmt) * [_fmt, " "] # default _fmt
for j, arg in enumerate( args ):
fmt = tf[ 2*j + 1 ]
if arg is None \
or isinstance( arg, basestring ) \
or (hasattr( arg, "__iter__" ) and len(arg) == 0):
tf[ 2*j + 1 ] = "%s" # %f -> %s, not error
continue
args[j], isarray = _tonumpyarray(arg)
if isarray and fmt[-1] in "defgEFG":
tf[ 2*j + 1 ] = "%s"
fmtfunc = (lambda x: fmt % x)
formatter = dict( float_kind=fmtfunc, int=fmtfunc )
args[j] = np.array2string( args[j], formatter=formatter )
try:
return "".join(tf) % tuple(args)
except TypeError: # shouldn't happen
print( "error: tf %s types %s" % (tf, map( type, args )))
raise
def _tonumpyarray( a ):
""" a, isarray = _tonumpyarray( a )
-> scalar, False
np.asanyarray(a), float or int
a, False
"""
a = getattr( a, "value", a ) # cvxpy
if np.isscalar(a):
return a, False
if hasattr( a, "__iter__" ) and len(a) == 0:
return a, False
try:
# map .value ?
a = np.asanyarray( a )
except ValueError:
return a, False
if hasattr( a, "dtype" ) and a.dtype.kind in "fi": # complex ?
if callable( _squeeze ):
a = _squeeze( a ) # np.squeeze
return a, True
else:
return a, False
#...............................................................................
if __name__ == "__main__":
import sys
n = 5
seed = 0
# run this.py n= ... in sh or ipython
for arg in sys.argv[1:]:
exec( arg )
np.set_printoptions( 1, threshold=4, edgeitems=2, linewidth=80, suppress=True )
np.random.seed(seed)
A = np.random.exponential( size=(n,n) ) ** 10
x = A[0]
printf( "x: %.3g \nA: %.1f \ns: %s \nB: %s ",
x, A, "str", A )
printf( "x %%d: %d", x )
printf( "x %%.0f: %.0f", x )
printf( "x %%.1e: %.1e", x )
printf( "x %%g: %g", x )
printf( "x %%s uses np printoptions: %s", x )
printf( "x with default _fmt: ", x )
printf( "no args" )
printf( "too few args: %g %g", x )
printf( x )
printf( x, x )
printf( None )
printf( "[]:", [] )
printf( "[3]:", [3] )
printf( np.array( [] ))
printf( [[]] ) # squeeze
Numpy 1.15(待定发布日期)将包含一个上下文管理器,用于在本地设置打印选项。这意味着下面的工作将与接受的答案(由unutbu和Neil G)中的相应示例相同,而无需编写自己的上下文管理器。举个例子:
x = np.random.random(10)
with np.printoptions(precision=3, suppress=True):
print(x)
# [ 0.073 0.461 0.689 0.754 0.624 0.901 0.049 0.582 0.557 0.348]
很惊讶没有看到周围的方法提到-意思是没有搞乱打印选项。
import numpy as np
x = np.random.random([5,5])
print(np.around(x,decimals=3))
Output:
[[0.475 0.239 0.183 0.991 0.171]
[0.231 0.188 0.235 0.335 0.049]
[0.87 0.212 0.219 0.9 0.3 ]
[0.628 0.791 0.409 0.5 0.319]
[0.614 0.84 0.812 0.4 0.307]]