當前位置: 首頁>>代碼示例>>Python>>正文


Python numpy.array2string方法代碼示例

本文整理匯總了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 
開發者ID:src-d,項目名稱:modelforge,代碼行數:26,代碼來源:slogging.py

示例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, ' ', "") 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:20,代碼來源:arrayprint.py

示例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) 
開發者ID:drscotthawley,項目名稱:signaltrain,代碼行數:20,代碼來源:viz.py

示例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) 
開發者ID:muhanzhang,項目名稱:D-VAE,代碼行數:20,代碼來源:formatting.py

示例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 
開發者ID:kishwarshafin,項目名稱:helen,代碼行數:23,代碼來源:dataloader_debug.py

示例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) 
開發者ID:chainer,項目名稱:chainer,代碼行數:24,代碼來源:variable.py

示例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) 
開發者ID:chainer,項目名稱:chainer,代碼行數:22,代碼來源:variable.py

示例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)) 
開發者ID:fab-jul,項目名稱:imgcomp-cvpr,代碼行數:7,代碼來源:logger.py

示例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) 
開發者ID:src-d,項目名稱:modelforge,代碼行數:8,代碼來源:slogging.py

示例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 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:41,代碼來源:arrayprint.py

示例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) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:10,代碼來源:test_arrayprint.py

示例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]"
        ) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:9,代碼來源:test_arrayprint.py

示例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]]]') 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:32,代碼來源:test_arrayprint.py

示例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) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:14,代碼來源:test_arrayprint.py

示例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') 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:38,代碼來源:test_arrayprint.py


注:本文中的numpy.array2string方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。