Python numpy.array2string() Examples
The following are 30
code examples of numpy.array2string().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
numpy
, or try the search function
.
Example #1
Source File: arrayprint.py From Mastering-Elasticsearch-7.0 with MIT License | 6 votes |
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, ' ', "")
Example #2
Source File: slogging.py From modelforge with Apache License 2.0 | 6 votes |
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
Example #3
Source File: dataloader_debug.py From helen with MIT License | 6 votes |
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
Example #4
Source File: viz.py From signaltrain with GNU General Public License v3.0 | 6 votes |
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)
Example #5
Source File: arrayprint.py From recruit with Apache License 2.0 | 6 votes |
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, ' ', "")
Example #6
Source File: formatting.py From D-VAE with MIT License | 6 votes |
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)
Example #7
Source File: variable.py From chainer with MIT License | 6 votes |
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)
Example #8
Source File: variable.py From chainer with MIT License | 6 votes |
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)
Example #9
Source File: test_arrayprint.py From GraphicDesignPatternByPython with MIT License | 5 votes |
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')
Example #10
Source File: test_arrayprint.py From Mastering-Elasticsearch-7.0 with MIT License | 5 votes |
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)
Example #11
Source File: m_of_n.py From pyMHT with BSD 3-Clause "New" or "Revised" License | 5 votes |
def __str__(self): formatter = {'float_kind': lambda x: "{: 7.1f}".format(x) } mmsiStr = " MMSI {:} ".format(self.mmsi) if self.mmsi is not None else "" predStateStr = ("Pred state:" + np.array2string(self.predicted_state, precision=1, suppress_small=True, formatter=formatter) if self.predicted_state is not None else "") return ("State: " + np.array2string(self.state, precision=1, suppress_small=True,formatter=formatter) + " ({0:}|{1:}) ".format(self.m, self.n) + predStateStr + mmsiStr)
Example #12
Source File: bayesopt.py From pybo with BSD 2-Clause "Simplified" License | 5 votes |
def array2str(a): """Formatting helper for arrays.""" return np.array2string(a, formatter=dict(float=float2str, int=int2str)) # THE BAYESOPT META SOLVER ####################################################
Example #13
Source File: test_datetime.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def test_datetime_array_str(self): a = np.array(['2011-03-16', '1920-01-01', '2013-05-19'], dtype='M') assert_equal(str(a), "['2011-03-16' '1920-01-01' '2013-05-19']") a = np.array(['2011-03-16T13:55', '1920-01-01T03:12'], dtype='M') assert_equal(np.array2string(a, separator=', ', formatter={'datetime': lambda x: "'%s'" % np.datetime_as_string(x, timezone='UTC')}), "['2011-03-16T13:55Z', '1920-01-01T03:12Z']") # Check that one NaT doesn't corrupt subsequent entries a = np.array(['2010', 'NaT', '2030']).astype('M') assert_equal(str(a), "['2010' 'NaT' '2030']")
Example #14
Source File: test_arrayprint.py From Computable with MIT License | 5 votes |
def test_format_function(self): """Test custom format function for each element in array.""" def _format_function(x): if np.abs(x) < 1: return '.' elif np.abs(x) < 2: return 'o' else: return 'O' x = np.arange(3) if sys.version_info[0] >= 3: x_hex = "[0x0 0x1 0x2]" x_oct = "[0o0 0o1 0o2]" else: x_hex = "[0x0L 0x1L 0x2L]" x_oct = "[0L 01L 02L]" assert_(np.array2string(x, formatter={'all':_format_function}) == \ "[. o O]") assert_(np.array2string(x, formatter={'int_kind':_format_function}) ==\ "[. o O]") assert_(np.array2string(x, formatter={'all':lambda x: "%.4f" % x}) == \ "[0.0000 1.0000 2.0000]") assert_equal(np.array2string(x, formatter={'int':lambda x: hex(x)}), \ x_hex) assert_equal(np.array2string(x, formatter={'int':lambda x: oct(x)}), \ x_oct) x = np.arange(3.) assert_(np.array2string(x, formatter={'float_kind':lambda x: "%.2f" % x}) == \ "[0.00 1.00 2.00]") assert_(np.array2string(x, formatter={'float':lambda x: "%.2f" % x}) == \ "[0.00 1.00 2.00]") s = np.array(['abc', 'def']) assert_(np.array2string(s, formatter={'numpystr':lambda s: s*2}) == \ '[abcabc defdef]')
Example #15
Source File: test_arrayprint.py From GraphicDesignPatternByPython with MIT License | 5 votes |
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)
Example #16
Source File: test_arrayprint.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def test_wide_element(self): a = np.array(['xxxxx']) assert_equal( np.array2string(a, max_line_width=5), "['xxxxx']" ) assert_equal( np.array2string(a, max_line_width=5, legacy='1.13'), "[ 'xxxxx']" )
Example #17
Source File: test_arrayprint.py From GraphicDesignPatternByPython with MIT License | 5 votes |
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]]]')
Example #18
Source File: test_arrayprint.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def test_basic(self): """Basic test of array2string.""" a = np.arange(3) assert_(np.array2string(a) == '[0 1 2]') assert_(np.array2string(a, max_line_width=4, legacy='1.13') == '[0 1\n 2]') assert_(np.array2string(a, max_line_width=4) == '[0\n 1\n 2]')
Example #19
Source File: test_arrayprint.py From Mastering-Elasticsearch-7.0 with MIT License | 5 votes |
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)
Example #20
Source File: arrayprint.py From Mastering-Elasticsearch-7.0 with MIT License | 5 votes |
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
Example #21
Source File: test_datetime.py From Computable with MIT License | 5 votes |
def test_datetime_array_str(self): a = np.array(['2011-03-16', '1920-01-01', '2013-05-19'], dtype='M') assert_equal(str(a), "['2011-03-16' '1920-01-01' '2013-05-19']") a = np.array(['2011-03-16T13:55Z', '1920-01-01T03:12Z'], dtype='M') assert_equal(np.array2string(a, separator=', ', formatter={'datetime': lambda x : "'%s'" % np.datetime_as_string(x, timezone='UTC')}), "['2011-03-16T13:55Z', '1920-01-01T03:12Z']")
Example #22
Source File: test_arrayprint.py From Mastering-Elasticsearch-7.0 with MIT License | 5 votes |
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]]]')
Example #23
Source File: test_arrayprint.py From Computable with MIT License | 5 votes |
def test_style_keyword(self): """This should only apply to 0-D arrays. See #1218.""" stylestr = np.array2string(np.array(1.5), style=lambda x: "Value in 0-D array: " + str(x)) assert_(stylestr == 'Value in 0-D array: 1.5')
Example #24
Source File: test_arrayprint.py From Computable with MIT License | 5 votes |
def test_basic(self): """Basic test of array2string.""" a = np.arange(3) assert_(np.array2string(a) == '[0 1 2]') assert_(np.array2string(a, max_line_width=4) == '[0 1\n 2]')
Example #25
Source File: array_printer.py From Computable with MIT License | 5 votes |
def array2string(a, max_line_width=None, precision=None, suppress_small=None, separator=' ', array_output=0): if array_output: prefix="array(" style=repr else: prefix = "" style=str return _array2string(a, max_line_width, precision, suppress_small, separator, prefix, style)
Example #26
Source File: slogging.py From fragile with MIT License | 5 votes |
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
Example #27
Source File: slogging.py From fragile with MIT License | 5 votes |
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)
Example #28
Source File: logger.py From imgcomp-cvpr with GNU General Public License v3.0 | 5 votes |
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))
Example #29
Source File: Vocabulary.py From pix2code with Apache License 2.0 | 5 votes |
def get_serialized_binary_representation(self): if len(self.binary_vocabulary) == 0: self.create_binary_representation() string = "" if sys.version_info >= (3,): items = self.binary_vocabulary.items() else: items = self.binary_vocabulary.iteritems() for key, value in items: array_as_string = np.array2string(value, separator=',', max_line_width=self.size * self.size) string += "{}{}{}\n".format(key, SEPARATOR, array_as_string[1:len(array_as_string) - 1]) return string
Example #30
Source File: test_datetime.py From vnpy_crypto with MIT License | 5 votes |
def test_datetime_array_str(self): a = np.array(['2011-03-16', '1920-01-01', '2013-05-19'], dtype='M') assert_equal(str(a), "['2011-03-16' '1920-01-01' '2013-05-19']") a = np.array(['2011-03-16T13:55', '1920-01-01T03:12'], dtype='M') assert_equal(np.array2string(a, separator=', ', formatter={'datetime': lambda x: "'%s'" % np.datetime_as_string(x, timezone='UTC')}), "['2011-03-16T13:55Z', '1920-01-01T03:12Z']") # Check that one NaT doesn't corrupt subsequent entries a = np.array(['2010', 'NaT', '2030']).astype('M') assert_equal(str(a), "['2010' 'NaT' '2030']")