本文整理汇总了Python中numpy.array2string方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.array2string方法的具体用法?Python numpy.array2string怎么用?Python numpy.array2string使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.array2string方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: getMessage
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import array2string [as 别名]
def getMessage(self):
"""
Return the message for this LogRecord.
Return the message for this LogRecord after merging any user-supplied \
arguments with the message.
"""
if isinstance(self.msg, numpy.ndarray):
msg = self.array2string(self.msg)
else:
msg = str(self.msg)
if self.args:
a2s = self.array2string
if isinstance(self.args, Dict):
args = {k: (a2s(v) if isinstance(v, numpy.ndarray) else v)
for (k, v) in self.args.items()}
elif isinstance(self.args, Sequence):
args = tuple((a2s(a) if isinstance(a, numpy.ndarray) else a)
for a in self.args)
else:
raise TypeError("Unexpected input '%s' with type '%s'" % (self.args,
type(self.args)))
msg = msg % args
return msg
示例2: _array_str_implementation
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import array2string [as 别名]
def _array_str_implementation(
a, max_line_width=None, precision=None, suppress_small=None,
array2string=array2string):
"""Internal version of array_str() that allows overriding array2string."""
if (_format_options['legacy'] == '1.13' and
a.shape == () and not a.dtype.names):
return str(a.item())
# the str of 0d arrays is a special case: It should appear like a scalar,
# so floats are not truncated by `precision`, and strings are not wrapped
# in quotes. So we return the str of the scalar value.
if a.shape == ():
# obtain a scalar and call str on it, avoiding problems for subclasses
# for which indexing with () returns a 0d instead of a scalar by using
# ndarray's getindex. Also guard against recursive 0d object arrays.
return _guarded_str(np.ndarray.__getitem__(a, ()))
return array2string(a, max_line_width, precision, suppress_small, ' ', "")
示例3: set_knobs
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import array2string [as 别名]
def set_knobs():
global knob_names, knobs_nn
setstr = 'global knobs_nn; knobs_nn = np.array(['
num_knobs = len(knob_names)
for i in range(len(knob_names)):
knob_name = knob_names[i]
setstr += f"{knob_name}"
if i < num_knobs-1: setstr += ','
setstr += '])'
#print('setstr = ',setstr)
exec(setstr)
#knobs_wc = knobs_nn * ()
knobs_wc = knob_ranges[:,0] + (knobs_nn+0.5)*(knob_ranges[:,1]-knob_ranges[:,0])
text = "knobs_wc = "+np.array2string(knobs_wc, precision=3, separator=',',suppress_small=True)
cv2.rectangle(logo, (0, 0), (500, 25), (255,255,255), -1)
cv2.putText(logo, text, (10, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.4, (0,0,0), lineType=cv2.LINE_AA)
cv2.imshow(knob_controls_window, logo)
示例4: var_label
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import array2string [as 别名]
def var_label(var, precision=3):
"""Return label of variable node."""
if var.name is not None:
return var.name
elif isinstance(var, gof.Constant):
h = np.asarray(var.data)
is_const = False
if h.ndim == 0:
is_const = True
h = np.array([h])
dstr = np.array2string(h, precision=precision)
if '\n' in dstr:
dstr = dstr[:dstr.index('\n')]
if is_const:
dstr = dstr.replace('[', '').replace(']', '')
return dstr
else:
return type_to_str(var.type)
示例5: __getitem__
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import array2string [as 别名]
def __getitem__(self, index):
"""
This method returns a single object. Dataloader uses this method to load images and then minibatches the loaded
images
:param index: Index indicating which image from all_images to be loaded
:return: image and their auxiliary information
"""
hdf5_filepath, image_name = self.all_images[index]
# load all the information we need to save in the prediction hdf5
with h5py.File(hdf5_filepath, 'r') as hdf5_file:
contig = np.array2string(hdf5_file['images'][image_name]['contig'][()][0].astype(np.str)).replace("'", '')
contig_start = hdf5_file['images'][image_name]['contig_start'][()][0].astype(np.int)
contig_end = hdf5_file['images'][image_name]['contig_end'][()][0].astype(np.int)
chunk_id = hdf5_file['images'][image_name]['feature_chunk_idx'][()][0].astype(np.int)
image = hdf5_file['images'][image_name]['image'][()].astype(np.uint8)
position = hdf5_file['images'][image_name]['position'][()].astype(np.int)
label_base = hdf5_file['images'][image_name]['label_base'][()]
label_run_length = hdf5_file['images'][image_name]['label_run_length'][()]
return image, label_base, label_run_length, position, contig, contig_start, contig_end, chunk_id, hdf5_filepath
示例6: variable_repr
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import array2string [as 别名]
def variable_repr(var):
"""Return the string representation of a variable.
Args:
var (~chainer.Variable): Input Variable.
.. seealso:: numpy.array_repr
"""
arr = _cpu._to_cpu(var.array)
if var.name:
prefix = 'variable ' + var.name
else:
prefix = 'variable'
if arr is None:
lst = 'None'
elif arr.size > 0 or arr.shape == (0,):
lst = numpy.array2string(arr, None, None, None, ', ', prefix + '(')
else: # show zero-length shape unless it is (0,)
lst = '[], shape=%s' % (repr(arr.shape),)
return '%s(%s)' % (prefix, lst)
示例7: variable_str
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import array2string [as 别名]
def variable_str(var):
"""Return the string representation of a variable.
Args:
var (~chainer.Variable): Input Variable.
.. seealso:: numpy.array_str
"""
arr = _cpu._to_cpu(var.array)
if var.name:
prefix = 'variable ' + var.name
else:
prefix = 'variable'
if arr is None:
lst = 'None'
else:
lst = numpy.array2string(arr, None, None, None, ' ', prefix + '(')
return '%s(%s)' % (prefix, lst)
示例8: __init__
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import array2string [as 别名]
def __init__(self, wrapper_str='{}', max_elements=None, precision=3, sep=','):
self._array2string = lambda _arr: wrapper_str.format(
np.array2string(
_arr.flatten()[:max_elements],
precision=precision, separator=sep))
示例9: array2string
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import array2string [as 别名]
def array2string(arr: numpy.ndarray) -> str:
"""Format numpy array as a string."""
shape = str(arr.shape)[1:-1]
if shape.endswith(","):
shape = shape[:-1]
return numpy.array2string(arr, threshold=11) + "%s[%s]" % (arr.dtype, shape)
示例10: array_str
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import array2string [as 别名]
def array_str(a, max_line_width=None, precision=None, suppress_small=None):
"""
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.
Parameters
----------
a : ndarray
Input array.
max_line_width : int, optional
Inserts newlines if text is longer than `max_line_width`. The
default is, indirectly, 75.
precision : int, optional
Floating point precision. Default is the current printing precision
(usually 8), which can be altered using `set_printoptions`.
suppress_small : bool, optional
Represent numbers "very close" to zero as zero; default is False.
Very close is defined by precision: if the precision is 8, e.g.,
numbers smaller (in absolute value) than 5e-9 are represented as
zero.
See Also
--------
array2string, array_repr, set_printoptions
Examples
--------
>>> np.array_str(np.arange(3))
'[0 1 2]'
"""
return _array_str_implementation(
a, max_line_width, precision, suppress_small)
# needed if __array_function__ is disabled
示例11: test_unexpected_kwarg
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import array2string [as 别名]
def test_unexpected_kwarg(self):
# ensure than an appropriate TypeError
# is raised when array2string receives
# an unexpected kwarg
with assert_raises_regex(TypeError, 'nonsense'):
np.array2string(np.array([1, 2, 3]),
nonsense=None)
示例12: test_edgeitems_kwarg
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import array2string [as 别名]
def test_edgeitems_kwarg(self):
# previously the global print options would be taken over the kwarg
arr = np.zeros(3, int)
assert_equal(
np.array2string(arr, edgeitems=1, threshold=0),
"[0 ... 0]"
)
示例13: test_linewidth
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import array2string [as 别名]
def test_linewidth(self):
a = np.full(6, 1)
def make_str(a, width, **kw):
return np.array2string(a, separator="", max_line_width=width, **kw)
assert_equal(make_str(a, 8, legacy='1.13'), '[111111]')
assert_equal(make_str(a, 7, legacy='1.13'), '[111111]')
assert_equal(make_str(a, 5, legacy='1.13'), '[1111\n'
' 11]')
assert_equal(make_str(a, 8), '[111111]')
assert_equal(make_str(a, 7), '[11111\n'
' 1]')
assert_equal(make_str(a, 5), '[111\n'
' 111]')
b = a[None,None,:]
assert_equal(make_str(b, 12, legacy='1.13'), '[[[111111]]]')
assert_equal(make_str(b, 9, legacy='1.13'), '[[[111111]]]')
assert_equal(make_str(b, 8, legacy='1.13'), '[[[11111\n'
' 1]]]')
assert_equal(make_str(b, 12), '[[[111111]]]')
assert_equal(make_str(b, 9), '[[[111\n'
' 111]]]')
assert_equal(make_str(b, 8), '[[[11\n'
' 11\n'
' 11]]]')
示例14: test_refcount
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import array2string [as 别名]
def test_refcount(self):
# make sure we do not hold references to the array due to a recursive
# closure (gh-10620)
gc.disable()
a = np.arange(2)
r1 = sys.getrefcount(a)
np.array2string(a)
np.array2string(a)
r2 = sys.getrefcount(a)
gc.collect()
gc.enable()
assert_(r1 == r2)
示例15: test_0d_arrays
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import array2string [as 别名]
def test_0d_arrays(self):
unicode = type(u'')
assert_equal(unicode(np.array(u'café', '<U4')), u'café')
if sys.version_info[0] >= 3:
assert_equal(repr(np.array('café', '<U4')),
"array('café', dtype='<U4')")
else:
assert_equal(repr(np.array(u'café', '<U4')),
"array(u'caf\\xe9', dtype='<U4')")
assert_equal(str(np.array('test', np.str_)), 'test')
a = np.zeros(1, dtype=[('a', '<i4', (3,))])
assert_equal(str(a[0]), '([0, 0, 0],)')
assert_equal(repr(np.datetime64('2005-02-25')[...]),
"array('2005-02-25', dtype='datetime64[D]')")
assert_equal(repr(np.timedelta64('10', 'Y')[...]),
"array(10, dtype='timedelta64[Y]')")
# repr of 0d arrays is affected by printoptions
x = np.array(1)
np.set_printoptions(formatter={'all':lambda x: "test"})
assert_equal(repr(x), "array(test)")
# str is unaffected
assert_equal(str(x), "1")
# check `style` arg raises
assert_warns(DeprecationWarning, np.array2string,
np.array(1.), style=repr)
# but not in legacy mode
np.array2string(np.array(1.), style=repr, legacy='1.13')
# gh-10934 style was broken in legacy mode, check it works
np.array2string(np.array(1.), legacy='1.13')