Python numpy.str_() Examples

The following are 30 code examples for showing how to use numpy.str_(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module numpy , or try the search function .

Example 1
Project: deepchem   Author: deepchem   File: pyanitools.py    License: MIT License 6 votes vote down vote up
def store_data(self, store_loc, **kwargs):
    """Put arrays to store
        """
    #print(store_loc)
    g = self.store.create_group(store_loc)
    for k, v, in kwargs.items():
      #print(type(v[0]))

      #print(k)
      if type(v) == list:
        if len(v) != 0:
          if type(v[0]) is np.str_ or type(v[0]) is str:
            v = [a.encode('utf8') for a in v]

      g.create_dataset(
          k, data=v, compression=self.clib, compression_opts=self.clev) 
Example 2
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_deprecations.py    License: MIT License 6 votes vote down vote up
def test_scalar_none_comparison(self):
        # Scalars should still just return False and not give a warnings.
        # The comparisons are flagged by pep8, ignore that.
        with warnings.catch_warnings(record=True) as w:
            warnings.filterwarnings('always', '', FutureWarning)
            assert_(not np.float32(1) == None)
            assert_(not np.str_('test') == None)
            # This is dubious (see below):
            assert_(not np.datetime64('NaT') == None)

            assert_(np.float32(1) != None)
            assert_(np.str_('test') != None)
            # This is dubious (see below):
            assert_(np.datetime64('NaT') != None)
        assert_(len(w) == 0)

        # For documentation purposes, this is why the datetime is dubious.
        # At the time of deprecation this was no behaviour change, but
        # it has to be considered when the deprecations are done.
        assert_(np.equal(np.datetime64('NaT'), None)) 
Example 3
Project: pyuvdata   Author: RadioAstronomySoftwareGroup   File: test_uvflag.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_to_waterfall_bl_multi_pol():
    uvf = UVFlag(test_f_file)
    uvf.weights_array = np.ones_like(uvf.weights_array)
    uvf2 = uvf.copy()
    uvf2.polarization_array[0] = -4
    uvf.__add__(uvf2, inplace=True, axis="pol")  # Concatenate to form multi-pol object
    uvf2 = uvf.copy()  # Keep a copy to run with keep_pol=False
    uvf.to_waterfall()
    assert uvf.type == "waterfall"
    assert uvf.metric_array.shape == (
        len(uvf.time_array),
        len(uvf.freq_array),
        len(uvf.polarization_array),
    )
    assert uvf.weights_array.shape == uvf.metric_array.shape
    assert len(uvf.polarization_array) == 2
    # Repeat with keep_pol=False
    uvf2.to_waterfall(keep_pol=False)
    assert uvf2.type == "waterfall"
    assert uvf2.metric_array.shape == (len(uvf2.time_array), len(uvf.freq_array), 1)
    assert uvf2.weights_array.shape == uvf2.metric_array.shape
    assert len(uvf2.polarization_array) == 1
    assert uvf2.polarization_array[0] == np.str_(
        ",".join(map(str, uvf.polarization_array))
    ) 
Example 4
Project: pyuvdata   Author: RadioAstronomySoftwareGroup   File: test_uvflag.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_collapse_pol_or():
    uvf = UVFlag(test_f_file)
    uvf.to_flag()
    assert uvf.weights_array is None
    uvf2 = uvf.copy()
    uvf2.polarization_array[0] = -4
    uvf.__add__(uvf2, inplace=True, axis="pol")  # Concatenate to form multi-pol object
    uvf2 = uvf.copy()
    uvf2.collapse_pol(method="or")
    assert len(uvf2.polarization_array) == 1
    assert uvf2.polarization_array[0] == np.str_(
        ",".join(map(str, uvf.polarization_array))
    )
    assert uvf2.mode == "flag"
    assert hasattr(uvf2, "flag_array")
    assert hasattr(uvf2, "metric_array")
    assert uvf2.metric_array is None 
Example 5
Project: pyuvdata   Author: RadioAstronomySoftwareGroup   File: test_uvflag.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_collapse_pol_flag():
    uvf = UVFlag(test_f_file)
    uvf.to_flag()
    assert uvf.weights_array is None
    uvf2 = uvf.copy()
    uvf2.polarization_array[0] = -4
    uvf.__add__(uvf2, inplace=True, axis="pol")  # Concatenate to form multi-pol object
    uvf2 = uvf.copy()
    uvf2.collapse_pol()
    assert len(uvf2.polarization_array) == 1
    assert uvf2.polarization_array[0] == np.str_(
        ",".join(map(str, uvf.polarization_array))
    )
    assert uvf2.mode == "metric"
    assert hasattr(uvf2, "metric_array")
    assert hasattr(uvf2, "flag_array")
    assert uvf2.flag_array is None 
Example 6
Project: kipoiseq   Author: kipoi   File: test_sequence.py    License: MIT License 6 votes vote down vote up
def test_fasta_based_dataset(intervals_file, fasta_file):
    # just test the functionality
    dl = StringSeqIntervalDl(intervals_file, fasta_file)
    ret_val = dl[0]
    assert isinstance(ret_val["inputs"], np.ndarray)
    assert ret_val["inputs"].shape == ()
    # # test with set wrong seqlen:
    # dl = StringSeqIntervalDl(intervals_file, fasta_file, required_seq_len=3)
    # with pytest.raises(Exception):
    #     dl[0]

    dl = StringSeqIntervalDl(intervals_file, fasta_file, label_dtype="str")
    ret_val = dl[0]
    assert isinstance(ret_val['targets'][0], np.str_)
    dl = StringSeqIntervalDl(intervals_file, fasta_file, label_dtype="int")
    ret_val = dl[0]
    assert isinstance(ret_val['targets'][0], np.int_)
    dl = StringSeqIntervalDl(intervals_file, fasta_file, label_dtype="bool")
    ret_val = dl[0]
    assert isinstance(ret_val['targets'][0], np.bool_)
    vals = dl.load_all()
    assert vals['inputs'][0] == 'GT' 
Example 7
def get_data(lst,preproc):
   data = []
   result = []
   for path in lst:
       f = dicom.read_file(path)
       img = preproc(f.pixel_array.astype(float) / np.max(f.pixel_array))
       dst_path = path.rsplit(".", 1)[0] + ".64x64.jpg"
       scipy.misc.imsave(dst_path, img)
       result.append(dst_path)
       data.append(img)
   data = np.array(data, dtype=np.uint8)
   data = data.reshape(data.size)
   data = np.array(data, dtype=np.str_)
   data = data.reshape(data.size)
   return [data,result] 
Example 8
Project: pyshgp   Author: erp12   File: test_types.py    License: MIT License 5 votes vote down vote up
def test_is_instance(self, core_type_lib):
        assert PushInt.is_instance(5)
        assert PushInt.is_instance(np.int64(100))
        assert not PushInt.is_instance("Foo")
        assert not PushInt.is_instance(np.str_("Bar"))

        assert not PushStr.is_instance(5)
        assert not PushStr.is_instance(np.int64(100))
        assert PushStr.is_instance("Foo")
        assert PushStr.is_instance(np.str_("Bar")) 
Example 9
Project: esmlab   Author: NCAR   File: core.py    License: Apache License 2.0 5 votes vote down vote up
def isdecoded(self, obj):
        return obj.dtype.type in {np.str_, np.object_, np.datetime64} 
Example 10
Project: recruit   Author: Frank-qlu   File: test_arrayprint.py    License: Apache License 2.0 5 votes vote down vote up
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 11
Project: recruit   Author: Frank-qlu   File: test_regression.py    License: Apache License 2.0 5 votes vote down vote up
def test_object_array_to_fixed_string(self):
        # Ticket #1235.
        a = np.array(['abcdefgh', 'ijklmnop'], dtype=np.object_)
        b = np.array(a, dtype=(np.str_, 8))
        assert_equal(a, b)
        c = np.array(a, dtype=(np.str_, 5))
        assert_equal(c, np.array(['abcde', 'ijklm']))
        d = np.array(a, dtype=(np.str_, 12))
        assert_equal(a, d)
        e = np.empty((2, ), dtype=(np.str_, 8))
        e[:] = a[:]
        assert_equal(a, e) 
Example 12
Project: recruit   Author: Frank-qlu   File: test_scalarmath.py    License: Apache License 2.0 5 votes vote down vote up
def test_scalar_comparison_to_none(self):
        # Scalars should just return False and not give a warnings.
        # The comparisons are flagged by pep8, ignore that.
        with warnings.catch_warnings(record=True) as w:
            warnings.filterwarnings('always', '', FutureWarning)
            assert_(not np.float32(1) == None)
            assert_(not np.str_('test') == None)
            # This is dubious (see below):
            assert_(not np.datetime64('NaT') == None)

            assert_(np.float32(1) != None)
            assert_(np.str_('test') != None)
            # This is dubious (see below):
            assert_(np.datetime64('NaT') != None)
        assert_(len(w) == 0)

        # For documentation purposes, this is why the datetime is dubious.
        # At the time of deprecation this was no behaviour change, but
        # it has to be considered when the deprecations are done.
        assert_(np.equal(np.datetime64('NaT'), None))


#class TestRepr(object):
#    def test_repr(self):
#        for t in types:
#            val = t(1197346475.0137341)
#            val_repr = repr(val)
#            val2 = eval(val_repr)
#            assert_equal( val, val2 ) 
Example 13
Project: recruit   Author: Frank-qlu   File: test_constructors.py    License: Apache License 2.0 5 votes vote down vote up
def test_constructor_empty_with_string_dtype(self):
        # GH 9428
        expected = DataFrame(index=[0, 1], columns=[0, 1], dtype=object)

        df = DataFrame(index=[0, 1], columns=[0, 1], dtype=str)
        tm.assert_frame_equal(df, expected)
        df = DataFrame(index=[0, 1], columns=[0, 1], dtype=np.str_)
        tm.assert_frame_equal(df, expected)
        df = DataFrame(index=[0, 1], columns=[0, 1], dtype=np.unicode_)
        tm.assert_frame_equal(df, expected)
        df = DataFrame(index=[0, 1], columns=[0, 1], dtype='U5')
        tm.assert_frame_equal(df, expected) 
Example 14
Project: recruit   Author: Frank-qlu   File: test_inference.py    License: Apache License 2.0 5 votes vote down vote up
def test_is_scalar_numpy_array_scalars(self):
        assert is_scalar(np.int64(1))
        assert is_scalar(np.float64(1.))
        assert is_scalar(np.int32(1))
        assert is_scalar(np.object_('foobar'))
        assert is_scalar(np.str_('foobar'))
        assert is_scalar(np.unicode_(u('foobar')))
        assert is_scalar(np.bytes_(b'foobar'))
        assert is_scalar(np.datetime64('2014-01-01'))
        assert is_scalar(np.timedelta64(1, 'h')) 
Example 15
Project: recruit   Author: Frank-qlu   File: testing.py    License: Apache License 2.0 5 votes vote down vote up
def rands_array(nchars, size, dtype='O'):
    """Generate an array of byte strings."""
    retval = (np.random.choice(RANDS_CHARS, size=nchars * np.prod(size))
              .view((np.str_, nchars)).reshape(size))
    if dtype is None:
        return retval
    else:
        return retval.astype(dtype) 
Example 16
Project: buzzard   Author: airware   File: _gdal_conv.py    License: Apache License 2.0 5 votes vote down vote up
def wkbgeom_of_str(str_):
    return _WKBGEOM_OF_STR[str_] 
Example 17
Project: buzzard   Author: airware   File: _gdal_conv.py    License: Apache License 2.0 5 votes vote down vote up
def type_of_oftstr(str_):
    return _TYPE_OF_OFT[_OFT_OF_STR[str_]]

# OF (Open Flag) <-> str ************************************************************************ ** 
Example 18
Project: buzzard   Author: airware   File: _gdal_conv.py    License: Apache License 2.0 5 votes vote down vote up
def of_of_str(str_):
    return _OF_OF_STR[str_] 
Example 19
Project: buzzard   Author: airware   File: _gdal_conv.py    License: Apache License 2.0 5 votes vote down vote up
def gci_of_str(str_):
    return _GCI_OF_STR[str_] 
Example 20
Project: buzzard   Author: airware   File: _gdal_conv.py    License: Apache License 2.0 5 votes vote down vote up
def gmf_of_str(str_):
    l = str_.replace(',', ' ').split(' ')
    l = [v for v in l if len(v)]

    diff = set(l) - set(_GMF_OF_STR.keys())
    if diff:
        raise ValueError('Unknown gmf %s' % diff)
    return sum(_GMF_OF_STR[elt] for elt in l) 
Example 21
Project: buzzard   Author: airware   File: _gdal_conv.py    License: Apache License 2.0 5 votes vote down vote up
def cple_of_str(str_):
    return _CPLE_OF_STR[str_] 
Example 22
Project: dexplo   Author: dexplo   File: _utils.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def is_string(value: Any) -> bool:
    return isinstance(value, (str, np.str_)) 
Example 23
Project: mars   Author: mars-project   File: core.py    License: Apache License 2.0 5 votes vote down vote up
def assert_dtype_consistent(expected_dtype, real_dtype):
        if isinstance(real_dtype, pd.DatetimeTZDtype):
            real_dtype = real_dtype.base
        if expected_dtype != real_dtype:
            if expected_dtype == np.dtype('O') and real_dtype.type is np.str_:
                # real dtype is string, this matches expectation
                return
            if expected_dtype is None:
                raise AssertionError('Expected dtype cannot be None')
            if not np.can_cast(real_dtype, expected_dtype) and not np.can_cast(expected_dtype, real_dtype):
                raise AssertionError('cannot cast between dtype of real dtype %r and dtype %r defined in metadata'
                                     % (real_dtype, expected_dtype)) 
Example 24
Project: mars   Author: mars-project   File: resource.py    License: Apache License 2.0 5 votes vote down vote up
def select_worker(self, size=None):
        # NB: randomly choice the indices, rather than the worker list to avoid the `str` to `np.str_` casting.
        available_workers = [k for k in self._meta_cache if k not in self._worker_blacklist]
        idx = np.random.choice(range(len(available_workers)), size=size)
        if size is None:
            return available_workers[idx]
        else:
            return [available_workers[i] for i in idx] 
Example 25
Project: paramz   Author: sods   File: observable_tests.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_casting(self):
        ints = np.array(range(10))
        self.assertEqual(ints.dtype, np.int_)
        floats = np.arange(0,5,.5)
        self.assertEqual(floats.dtype, np.float_)
        strings = np.array(list('testing'))
        self.assertEqual(strings.dtype.type, np.str_)

        self.assertEqual(ObsAr(ints).dtype, np.float_)
        self.assertEqual(ObsAr(floats).dtype, np.float_)
        self.assertEqual(ObsAr(strings).dtype.type, np.str_) 
Example 26
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_regression.py    License: MIT License 5 votes vote down vote up
def test_object_array_to_fixed_string(self):
        # Ticket #1235.
        a = np.array(['abcdefgh', 'ijklmnop'], dtype=np.object_)
        b = np.array(a, dtype=(np.str_, 8))
        assert_equal(a, b)
        c = np.array(a, dtype=(np.str_, 5))
        assert_equal(c, np.array(['abcde', 'ijklm']))
        d = np.array(a, dtype=(np.str_, 12))
        assert_equal(a, d)
        e = np.empty((2, ), dtype=(np.str_, 8))
        e[:] = a[:]
        assert_equal(a, e) 
Example 27
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: debug_data_test.py    License: MIT License 5 votes vote down vote up
def testDTypeObjectGivesFalse(self):
    dt = np.dtype([("spam", np.str_, 16), ("eggs", np.float64, (2,))])
    a = np.array([("spam", (8.0, 7.0)), ("eggs", (6.0, 5.0))], dtype=dt)
    self.assertFalse(debug_data.has_inf_or_nan(self._dummy_datum, a)) 
Example 28
Project: vnpy_crypto   Author: birforce   File: test_arrayprint.py    License: MIT License 5 votes vote down vote up
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 29
Project: vnpy_crypto   Author: birforce   File: test_regression.py    License: MIT License 5 votes vote down vote up
def test_object_array_to_fixed_string(self):
        # Ticket #1235.
        a = np.array(['abcdefgh', 'ijklmnop'], dtype=np.object_)
        b = np.array(a, dtype=(np.str_, 8))
        assert_equal(a, b)
        c = np.array(a, dtype=(np.str_, 5))
        assert_equal(c, np.array(['abcde', 'ijklm']))
        d = np.array(a, dtype=(np.str_, 12))
        assert_equal(a, d)
        e = np.empty((2, ), dtype=(np.str_, 8))
        e[:] = a[:]
        assert_equal(a, e) 
Example 30
Project: vnpy_crypto   Author: birforce   File: test_dtypes.py    License: MIT License 5 votes vote down vote up
def test_numpy_informed(self):
        pytest.raises(TypeError, np.dtype, self.dtype)

        assert not self.dtype == np.str_
        assert not np.str_ == self.dtype