Python numpy.string_() Examples

The following are 30 code examples for showing how to use numpy.string_(). 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: EXOSIMS   Author: dsavransky   File: TargetList.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def nan_filter(self):
        """Populates Target List and filters out values which are nan
        
        """
        
        # filter out nan values in numerical attributes
        for att in self.catalog_atts:
            if ('close' in att) or ('bright' in att):
                continue
            if getattr(self, att).shape[0] == 0:
                pass
            elif (type(getattr(self, att)[0]) == str) or (type(getattr(self, att)[0]) == bytes):
                # FIXME: intent here unclear: 
                #   note float('nan') is an IEEE NaN, getattr(.) is a str, and != on NaNs is special
                i = np.where(getattr(self, att) != float('nan'))[0]
                self.revise_lists(i)
            # exclude non-numerical types
            elif type(getattr(self, att)[0]) not in (np.unicode_, np.string_, np.bool_, bytes):
                if att == 'coords':
                    i1 = np.where(~np.isnan(self.coords.ra.to('deg').value))[0]
                    i2 = np.where(~np.isnan(self.coords.dec.to('deg').value))[0]
                    i = np.intersect1d(i1,i2)
                else:
                    i = np.where(~np.isnan(getattr(self, att)))[0]
                self.revise_lists(i) 
Example 2
Project: BetaElephant   Author: milkpku   File: datatransfer.py    License: MIT License 6 votes vote down vote up
def fen2state(fen):
    '''
    transfer the fen string to chessboard
    fen: fen string
    return: state of the chessboard
    '''
    fenstrlist = fen.split()
    cstate = chessboradstate()
    cstate.state = np.zeros([10, 9], np.string_)
    fenstr1st = fenstrlist[0].split('/')
    for i in range(len(fenstr1st)):
        current = 0
        for j in range(len(fenstr1st[i])):
            if fenstr1st[i][j].isdigit():
                num = int(fenstr1st[i][j])
                for k in range(num):
                    cstate.state[i][current+k] = ' '
                current += num
            else:
                cstate.state[i][current] = fenstr1st[i][j]
                current += 1
    cstate.turn = fenstrlist[1]
    cstate.roundcnt = int(fenstrlist[5])
    return cstate 
Example 3
Project: BetaElephant   Author: milkpku   File: datatransfer.py    License: MIT License 6 votes vote down vote up
def move(cstate, move):
    '''
    move the chess according to the move action
    state: the current chessborad, numpy.array[10][9], dtype=string_
    move: the action to move, string format as:'D5-E5'
    '''
    src = []
    des = []
    src.append(9 - int(move[1]))
    src.append(ord(move[0]) - ord('A'))
    des.append(9 - int(move[4]))
    des.append(ord(move[3]) - ord('A'))
    # print src, des
    chess = cstate.state[src[0]][src[1]]
    cstate.state[src[0]][src[1]] = ' '
    cstate.state[des[0]][des[1]] = chess
    cstate.roundcnt += 1
    if cstate.turn == 'b':
        cstate.turn = 'w'
    else:
        cstate.turn = 'b' 
Example 4
Project: recruit   Author: Frank-qlu   File: test_scalarinherit.py    License: Apache License 2.0 6 votes vote down vote up
def test_char_radd(self):
        # GH issue 9620, reached gentype_add and raise TypeError
        np_s = np.string_('abc')
        np_u = np.unicode_('abc')
        s = b'def'
        u = u'def'
        assert_(np_s.__radd__(np_s) is NotImplemented)
        assert_(np_s.__radd__(np_u) is NotImplemented)
        assert_(np_s.__radd__(s) is NotImplemented)
        assert_(np_s.__radd__(u) is NotImplemented)
        assert_(np_u.__radd__(np_s) is NotImplemented)
        assert_(np_u.__radd__(np_u) is NotImplemented)
        assert_(np_u.__radd__(s) is NotImplemented)
        assert_(np_u.__radd__(u) is NotImplemented)
        assert_(s + np_s == b'defabc')
        assert_(u + np_u == u'defabc')


        class Mystr(str, np.generic):
            # would segfault
            pass

        ret = s + Mystr('abc')
        assert_(type(ret) is type(s)) 
Example 5
Project: recruit   Author: Frank-qlu   File: test_defchararray.py    License: Apache License 2.0 6 votes vote down vote up
def test_from_string_array(self):
        A = np.array([[b'abc', b'foo'],
                      [b'long   ', b'0123456789']])
        assert_equal(A.dtype.type, np.string_)
        B = np.char.array(A)
        assert_array_equal(B, A)
        assert_equal(B.dtype, A.dtype)
        assert_equal(B.shape, A.shape)
        B[0, 0] = 'changed'
        assert_(B[0, 0] != A[0, 0])
        C = np.char.asarray(A)
        assert_array_equal(C, A)
        assert_equal(C.dtype, A.dtype)
        C[0, 0] = 'changed again'
        assert_(C[0, 0] != B[0, 0])
        assert_(C[0, 0] == A[0, 0]) 
Example 6
Project: recruit   Author: Frank-qlu   File: test_defchararray.py    License: Apache License 2.0 6 votes vote down vote up
def test_join(self):
        if sys.version_info[0] >= 3:
            # NOTE: list(b'123') == [49, 50, 51]
            #       so that b','.join(b'123') results to an error on Py3
            A0 = self.A.decode('ascii')
        else:
            A0 = self.A

        A = np.char.join([',', '#'], A0)
        if sys.version_info[0] >= 3:
            assert_(issubclass(A.dtype.type, np.unicode_))
        else:
            assert_(issubclass(A.dtype.type, np.string_))
        tgt = np.array([[' ,a,b,c, ', ''],
                        ['1,2,3,4,5', 'M#i#x#e#d#C#a#s#e'],
                        ['1,2,3, ,\t, ,3,4,5, ,\x00, ', 'U#P#P#E#R']])
        assert_array_equal(np.char.join([',', '#'], A0), tgt) 
Example 7
Project: recruit   Author: Frank-qlu   File: test_defchararray.py    License: Apache License 2.0 6 votes vote down vote up
def test_ljust(self):
        assert_(issubclass(self.A.ljust(10).dtype.type, np.string_))

        C = self.A.ljust([10, 20])
        assert_array_equal(np.char.str_len(C), [[10, 20], [10, 20], [12, 20]])

        C = self.A.ljust(20, b'#')
        assert_array_equal(C.startswith(b'#'), [
                [False, True], [False, False], [False, False]])
        assert_(np.all(C.endswith(b'#')))

        C = np.char.ljust(b'FOO', [[10, 20], [15, 8]])
        tgt = [[b'FOO       ', b'FOO                 '],
               [b'FOO            ', b'FOO     ']]
        assert_(issubclass(C.dtype.type, np.string_))
        assert_array_equal(C, tgt) 
Example 8
Project: recruit   Author: Frank-qlu   File: test_defchararray.py    License: Apache License 2.0 6 votes vote down vote up
def test_lstrip(self):
        tgt = [[b'abc ', b''],
               [b'12345', b'MixedCase'],
               [b'123 \t 345 \0 ', b'UPPER']]
        assert_(issubclass(self.A.lstrip().dtype.type, np.string_))
        assert_array_equal(self.A.lstrip(), tgt)

        tgt = [[b' abc', b''],
               [b'2345', b'ixedCase'],
               [b'23 \t 345 \x00', b'UPPER']]
        assert_array_equal(self.A.lstrip([b'1', b'M']), tgt)

        tgt = [[u'\u03a3 ', ''],
               ['12345', 'MixedCase'],
               ['123 \t 345 \0 ', 'UPPER']]
        assert_(issubclass(self.B.lstrip().dtype.type, np.unicode_))
        assert_array_equal(self.B.lstrip(), tgt) 
Example 9
Project: recruit   Author: Frank-qlu   File: test_defchararray.py    License: Apache License 2.0 6 votes vote down vote up
def test_rjust(self):
        assert_(issubclass(self.A.rjust(10).dtype.type, np.string_))

        C = self.A.rjust([10, 20])
        assert_array_equal(np.char.str_len(C), [[10, 20], [10, 20], [12, 20]])

        C = self.A.rjust(20, b'#')
        assert_(np.all(C.startswith(b'#')))
        assert_array_equal(C.endswith(b'#'),
                           [[False, True], [False, False], [False, False]])

        C = np.char.rjust(b'FOO', [[10, 20], [15, 8]])
        tgt = [[b'       FOO', b'                 FOO'],
               [b'            FOO', b'     FOO']]
        assert_(issubclass(C.dtype.type, np.string_))
        assert_array_equal(C, tgt) 
Example 10
Project: recruit   Author: Frank-qlu   File: test_defchararray.py    License: Apache License 2.0 6 votes vote down vote up
def test_rstrip(self):
        assert_(issubclass(self.A.rstrip().dtype.type, np.string_))

        tgt = [[b' abc', b''],
               [b'12345', b'MixedCase'],
               [b'123 \t 345', b'UPPER']]
        assert_array_equal(self.A.rstrip(), tgt)

        tgt = [[b' abc ', b''],
               [b'1234', b'MixedCase'],
               [b'123 \t 345 \x00', b'UPP']
               ]
        assert_array_equal(self.A.rstrip([b'5', b'ER']), tgt)

        tgt = [[u' \u03a3', ''],
               ['12345', 'MixedCase'],
               ['123 \t 345', 'UPPER']]
        assert_(issubclass(self.B.rstrip().dtype.type, np.unicode_))
        assert_array_equal(self.B.rstrip(), tgt) 
Example 11
Project: recruit   Author: Frank-qlu   File: test_defchararray.py    License: Apache License 2.0 6 votes vote down vote up
def test_strip(self):
        tgt = [[b'abc', b''],
               [b'12345', b'MixedCase'],
               [b'123 \t 345', b'UPPER']]
        assert_(issubclass(self.A.strip().dtype.type, np.string_))
        assert_array_equal(self.A.strip(), tgt)

        tgt = [[b' abc ', b''],
               [b'234', b'ixedCas'],
               [b'23 \t 345 \x00', b'UPP']]
        assert_array_equal(self.A.strip([b'15', b'EReM']), tgt)

        tgt = [[u'\u03a3', ''],
               ['12345', 'MixedCase'],
               ['123 \t 345', 'UPPER']]
        assert_(issubclass(self.B.strip().dtype.type, np.unicode_))
        assert_array_equal(self.B.strip(), tgt) 
Example 12
Project: recruit   Author: Frank-qlu   File: defchararray.py    License: Apache License 2.0 6 votes vote down vote up
def add(x1, x2):
    """
    Return element-wise string concatenation for two arrays of str or unicode.

    Arrays `x1` and `x2` must have the same shape.

    Parameters
    ----------
    x1 : array_like of str or unicode
        Input array.
    x2 : array_like of str or unicode
        Input array.

    Returns
    -------
    add : ndarray
        Output array of `string_` or `unicode_`, depending on input types
        of the same shape as `x1` and `x2`.

    """
    arr1 = numpy.asarray(x1)
    arr2 = numpy.asarray(x2)
    out_size = _get_num_chars(arr1) + _get_num_chars(arr2)
    dtype = _use_unicode(arr1, arr2)
    return _vec_string(arr1, (dtype, out_size), '__add__', (arr2,)) 
Example 13
Project: westpa   Author: westpa   File: h5io.py    License: MIT License 6 votes vote down vote up
def label_axes(h5object, labels, units=None):
    '''Stamp the given HDF5 object with axis labels. This stores the axis labels
    in an array of strings in an attribute called ``axis_labels`` on the given
    object. ``units`` if provided is a corresponding list of units.'''
    
    if len(labels) != len(h5object.shape):
        raise ValueError('number of axes and number of labels do not match')
    
    if units is None: units = []
    
    if len(units) and len(units) != len(labels):
        raise ValueError('number of units labels does not match number of axes')
    
    h5object.attrs['axis_labels'] = numpy.array([numpy.string_(i) for i in labels])
     
    if len(units):
        h5object.attrs['axis_units'] = numpy.array([numpy.string_(i) for i in units]) 
Example 14
Project: lambda-packs   Author: ryfeus   File: defchararray.py    License: MIT License 6 votes vote down vote up
def add(x1, x2):
    """
    Return element-wise string concatenation for two arrays of str or unicode.

    Arrays `x1` and `x2` must have the same shape.

    Parameters
    ----------
    x1 : array_like of str or unicode
        Input array.
    x2 : array_like of str or unicode
        Input array.

    Returns
    -------
    add : ndarray
        Output array of `string_` or `unicode_`, depending on input types
        of the same shape as `x1` and `x2`.

    """
    arr1 = numpy.asarray(x1)
    arr2 = numpy.asarray(x2)
    out_size = _get_num_chars(arr1) + _get_num_chars(arr2)
    dtype = _use_unicode(arr1, arr2)
    return _vec_string(arr1, (dtype, out_size), '__add__', (arr2,)) 
Example 15
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_defchararray.py    License: MIT License 6 votes vote down vote up
def test_from_string_array(self):
        A = np.array(asbytes_nested([['abc', 'foo'],
                                     ['long   ', '0123456789']]))
        assert_equal(A.dtype.type, np.string_)
        B = np.char.array(A)
        assert_array_equal(B, A)
        assert_equal(B.dtype, A.dtype)
        assert_equal(B.shape, A.shape)
        B[0, 0] = 'changed'
        assert_(B[0, 0] != A[0, 0])
        C = np.char.asarray(A)
        assert_array_equal(C, A)
        assert_equal(C.dtype, A.dtype)
        C[0, 0] = 'changed again'
        assert_(C[0, 0] != B[0, 0])
        assert_(C[0, 0] == A[0, 0]) 
Example 16
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_defchararray.py    License: MIT License 6 votes vote down vote up
def test_join(self):
        if sys.version_info[0] >= 3:
            # NOTE: list(b'123') == [49, 50, 51]
            #       so that b','.join(b'123') results to an error on Py3
            A0 = self.A.decode('ascii')
        else:
            A0 = self.A

        A = np.char.join([',', '#'], A0)
        if sys.version_info[0] >= 3:
            assert_(issubclass(A.dtype.type, np.unicode_))
        else:
            assert_(issubclass(A.dtype.type, np.string_))
        tgt = np.array([[' ,a,b,c, ', ''],
                        ['1,2,3,4,5', 'M#i#x#e#d#C#a#s#e'],
                        ['1,2,3, ,\t, ,3,4,5, ,\x00, ', 'U#P#P#E#R']])
        assert_array_equal(np.char.join([',', '#'], A0), tgt) 
Example 17
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_defchararray.py    License: MIT License 6 votes vote down vote up
def test_ljust(self):
        assert_(issubclass(self.A.ljust(10).dtype.type, np.string_))

        C = self.A.ljust([10, 20])
        assert_array_equal(np.char.str_len(C), [[10, 20], [10, 20], [12, 20]])

        C = self.A.ljust(20, asbytes('#'))
        assert_array_equal(C.startswith(asbytes('#')), [
                [False, True], [False, False], [False, False]])
        assert_(np.all(C.endswith(asbytes('#'))))

        C = np.char.ljust(asbytes('FOO'), [[10, 20], [15, 8]])
        tgt = asbytes_nested([['FOO       ', 'FOO                 '],
                              ['FOO            ', 'FOO     ']])
        assert_(issubclass(C.dtype.type, np.string_))
        assert_array_equal(C, tgt) 
Example 18
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_defchararray.py    License: MIT License 6 votes vote down vote up
def test_replace(self):
        R = self.A.replace(asbytes_nested(['3', 'a']),
                           asbytes_nested(['##########', '@']))
        tgt = asbytes_nested([[' abc ', ''],
                              ['12##########45', 'MixedC@se'],
                              ['12########## \t ##########45 \x00', 'UPPER']])
        assert_(issubclass(R.dtype.type, np.string_))
        assert_array_equal(R, tgt)

        if sys.version_info[0] < 3:
            # NOTE: b'abc'.replace(b'a', 'b') is not allowed on Py3
            R = self.A.replace(asbytes('a'), sixu('\u03a3'))
            tgt = [[sixu(' \u03a3bc '), ''],
                   ['12345', sixu('MixedC\u03a3se')],
                   ['123 \t 345 \x00', 'UPPER']]
            assert_(issubclass(R.dtype.type, np.unicode_))
            assert_array_equal(R, tgt) 
Example 19
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_defchararray.py    License: MIT License 6 votes vote down vote up
def test_rjust(self):
        assert_(issubclass(self.A.rjust(10).dtype.type, np.string_))

        C = self.A.rjust([10, 20])
        assert_array_equal(np.char.str_len(C), [[10, 20], [10, 20], [12, 20]])

        C = self.A.rjust(20, asbytes('#'))
        assert_(np.all(C.startswith(asbytes('#'))))
        assert_array_equal(C.endswith(asbytes('#')),
                           [[False, True], [False, False], [False, False]])

        C = np.char.rjust(asbytes('FOO'), [[10, 20], [15, 8]])
        tgt = asbytes_nested([['       FOO', '                 FOO'],
                              ['            FOO', '     FOO']])
        assert_(issubclass(C.dtype.type, np.string_))
        assert_array_equal(C, tgt) 
Example 20
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_defchararray.py    License: MIT License 6 votes vote down vote up
def test_rstrip(self):
        assert_(issubclass(self.A.rstrip().dtype.type, np.string_))

        tgt = asbytes_nested([[' abc', ''],
                              ['12345', 'MixedCase'],
                              ['123 \t 345', 'UPPER']])
        assert_array_equal(self.A.rstrip(), tgt)

        tgt = asbytes_nested([[' abc ', ''],
                              ['1234', 'MixedCase'],
                              ['123 \t 345 \x00', 'UPP']
                              ])
        assert_array_equal(self.A.rstrip(asbytes_nested(['5', 'ER'])), tgt)

        tgt = [[sixu(' \u03a3'), ''],
               ['12345', 'MixedCase'],
               ['123 \t 345', 'UPPER']]
        assert_(issubclass(self.B.rstrip().dtype.type, np.unicode_))
        assert_array_equal(self.B.rstrip(), tgt) 
Example 21
Project: models   Author: kipoi   File: test_model.py    License: MIT License 5 votes vote down vote up
def setUp(self):
        self.soi_g80 = []
        for i in range(10): #generate test sequences
            length = random.randint(101, 1000)
            self.soi_g80.append( ''.join( random.choices(['A', 'C', 'G', 'T', 'a', 'c', 'g', 't'], k = length) ) )
        self.soi_g80 = np.array(self.soi_g80, dtype = np.string_)
        self.features_metadata = model.load_features_metadata() 
Example 22
Project: models   Author: kipoi   File: test_model.py    License: MIT License 5 votes vote down vote up
def setUp(self):
        self.soi_g80 = []
        for i in range(10):  # generate test sequences
            length = random.randint(101, 1000)
            self.soi_g80.append(''.join(random.choices(['A', 'C', 'G', 'T', 'a', 'c', 'g', 't'], k=length)))
        self.soi_g80 = np.array(self.soi_g80, dtype=np.string_)
        self.features_metadata = model.load_features_metadata() 
Example 23
Project: QCElemental   Author: MolSSI   File: types.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None:
        dt = cls._dtype
        if dt is int or np.issubdtype(dt, np.integer):
            items = {"type": "number", "multipleOf": 1.0}
        elif dt is float or np.issubdtype(dt, np.floating):
            items = {"type": "number"}
        elif dt is str or np.issubdtype(dt, np.string_):
            items = {"type": "string"}
        elif dt is bool or np.issubdtype(dt, np.bool_):
            items = {"type": "boolean"}
        field_schema.update(type="array", items=items) 
Example 24
Project: simnibs   Author: simnibs   File: gpc.py    License: GNU General Public License v3.0 5 votes vote down vote up
def save_hdf5(self, data_file=None):
        """ Saves the gPC information in an hdf5 file
        pdftype, pdfshape, limits, poly_idx and coords_norm are saved
        in "gpc_object" in the data file

        Parameters:
        -----------------
        data_file (optional): str
            name of data file. default: self.data_file

        """
        if data_file is None:
            data_file = self.data_file
        if data_file is None:
            raise ValueError('Please specify a data file')
        with h5py.File(data_file, 'a') as f:
            f.attrs['type'] = self.sim_type
            if 'gpc_object' in f.keys():
                del f['gpc_object']
            f.create_dataset('gpc_object/random_vars',
                             data=np.array(self.random_vars, dtype=np.string_))
            f.create_dataset('gpc_object/pdftype',
                             data=np.array(self.pdftype, dtype='S10'))
            f.create_dataset('gpc_object/pdfshape',
                             data=np.array(self.pdfshape))
            lim = [[], []]
            lim[0] = [l if l is not None else -1e10 for l in self.limits[0]]
            lim[1] = [l if l is not None else 1e10 for l in self.limits[1]]
            f.create_dataset('gpc_object/limits',
                             data=np.array(lim))
            f.create_dataset('gpc_object/poly_idx',
                             data=np.array(self.poly_idx))
            f.create_dataset('gpc_object/grid/coords_norm',
                             data=np.array(self.grid.coords_norm))
            f.create_dataset('gpc_object/regularization_factors',
                             data=np.array(self.regularization_factors)) 
Example 25
Project: simnibs   Author: simnibs   File: gpc.py    License: GNU General Public License v3.0 5 votes vote down vote up
def create_hdf5(self):
        super(TMSgPCSampler, self).create_hdf5()
        with h5py.File(self.fn_hdf5, 'a') as f:
            f.create_dataset('matsimnibs', data=self.matsimnibs)
            f.create_dataset('didt', data=np.array(self.didt, dtype=float))
            f.create_dataset('fnamecoil', data=np.array(self.fnamecoil, dtype=np.string_)) 
Example 26
Project: simnibs   Author: simnibs   File: sim_struct.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _write_conductivity_to_hdf5(self, fn_hdf5, path='cond/'):
        """
        Parameters
        -----------
        fn_hdf5: str
            file name of hdf5 file
        path: str
            path in the hdf5 file where the conductivity information should be saved
        """
        with h5py.File(fn_hdf5, 'a') as f:
            try:
                g = f.create_group(path)
            except ValueError:
                g = f[path]
            value_array = np.array([c.value for c in self.cond], dtype=float)
            g.create_dataset('values', data=value_array)
            g.create_dataset('names',
                             data=np.array([c.name for c in self.cond],
                                           dtype=np.string_))
            g.create_dataset('distribution_types',
                             data=np.array(
                                 [c.distribution_type for c in self.cond],
                                 dtype=np.string_))

            distribution_parameters = np.nan * np.zeros((len(self.cond), 4), dtype=float)
            for i, c in enumerate(self.cond):
                distribution_parameters[i, :len(c.distribution_parameters)] = c.distribution_parameters
            g.create_dataset('distribution_parameters',
                             data=distribution_parameters)
            g.attrs['anisotropic_tissues'] = self.anisotropic_tissues
            g.attrs['anisotropy_type'] = self.anisotropy_type
            aniso = False
            if self.anisotropy_type in ['dir', 'vn', 'mc']:
                image, affine = self._get_vol_info()
                g.create_dataset('anisotropy_vol', data=image)
                g.create_dataset('anisotropy_affine', data=affine) 
Example 27
Project: BetaElephant   Author: milkpku   File: datatransfer.py    License: MIT License 5 votes vote down vote up
def __init__(self):
        self.state = np.zeros([10,9], dtype=np.string_)
        self.turn = 'w'
        self.roundcnt = 1 
Example 28
Project: arctic   Author: man-group   File: incremental.py    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
def _dtype_convert_to_max_len_string(self, input_ndtype, fname):
        if input_ndtype.type not in (np.string_, np.unicode_):
            return input_ndtype, False
        type_sym = 'S' if input_ndtype.type == np.string_ else 'U'
        max_str_len = len(max(self.input_data[fname].astype(type_sym), key=len))
        str_field_dtype = np.dtype('{}{:d}'.format(type_sym, max_str_len)) if max_str_len > 0 else input_ndtype
        return str_field_dtype, True 
Example 29
Project: recruit   Author: Frank-qlu   File: test_scalarinherit.py    License: Apache License 2.0 5 votes vote down vote up
def test_char_repeat(self):
        np_s = np.string_('abc')
        np_u = np.unicode_('abc')
        np_i = np.int(5)
        res_s = b'abc' * 5
        res_u = u'abc' * 5
        assert_(np_s * np_i == res_s)
        assert_(np_u * np_i == res_u) 
Example 30
Project: recruit   Author: Frank-qlu   File: test_datetime.py    License: Apache License 2.0 5 votes vote down vote up
def test_datetime_string_conversion(self):
        a = ['2011-03-16', '1920-01-01', '2013-05-19']
        str_a = np.array(a, dtype='S')
        uni_a = np.array(a, dtype='U')
        dt_a = np.array(a, dtype='M')

        # String to datetime
        assert_equal(dt_a, str_a.astype('M'))
        assert_equal(dt_a.dtype, str_a.astype('M').dtype)
        dt_b = np.empty_like(dt_a)
        dt_b[...] = str_a
        assert_equal(dt_a, dt_b)

        # Datetime to string
        assert_equal(str_a, dt_a.astype('S0'))
        str_b = np.empty_like(str_a)
        str_b[...] = dt_a
        assert_equal(str_a, str_b)

        # Unicode to datetime
        assert_equal(dt_a, uni_a.astype('M'))
        assert_equal(dt_a.dtype, uni_a.astype('M').dtype)
        dt_b = np.empty_like(dt_a)
        dt_b[...] = uni_a
        assert_equal(dt_a, dt_b)

        # Datetime to unicode
        assert_equal(uni_a, dt_a.astype('U'))
        uni_b = np.empty_like(uni_a)
        uni_b[...] = dt_a
        assert_equal(uni_a, uni_b)

        # Datetime to long string - gh-9712
        assert_equal(str_a, dt_a.astype((np.string_, 128)))
        str_b = np.empty(str_a.shape, dtype=(np.string_, 128))
        str_b[...] = dt_a
        assert_equal(str_a, str_b)