Python numpy.object() Examples

The following are 30 code examples of numpy.object(). 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: TargetingSystem.py    From poeai with MIT License 7 votes vote down vote up
def Train(self, C, A, Y, SF):
        '''
        Train the classifier using the sample matrix A and target matrix Y
        '''
        C.fit(A, Y)
        YH = np.zeros(Y.shape, dtype = np.object)
        for i in np.array_split(np.arange(A.shape[0]), 32):   #Split up verification into chunks to prevent out of memory
            YH[i] = C.predict(A[i])
        s1 = SF(Y, YH)
        print('All:{:8.6f}'.format(s1))
        '''
        ss = ShuffleSplit(random_state = 1151)  #Use fixed state for so training can be repeated later
        trn, tst = next(ss.split(A, Y))         #Make train/test split
        mi = [8] * 1                            #Maximum number of iterations at each iter
        YH = np.zeros((A.shape[0]), dtype = np.object)
        for mic in mi:                                      #Chunk size to split dataset for CV results
            #C.SetMaxIter(mic)                               #Set the maximum number of iterations to run
            #C.fit(A[trn], Y[trn])                           #Perform training iterations
        ''' 
Example #2
Source File: test_apply.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_apply(self, datetime_series):
        with np.errstate(all='ignore'):
            tm.assert_series_equal(datetime_series.apply(np.sqrt),
                                   np.sqrt(datetime_series))

            # element-wise apply
            import math
            tm.assert_series_equal(datetime_series.apply(math.exp),
                                   np.exp(datetime_series))

        # empty series
        s = Series(dtype=object, name='foo', index=pd.Index([], name='bar'))
        rs = s.apply(lambda x: x)
        tm.assert_series_equal(s, rs)

        # check all metadata (GH 9322)
        assert s is not rs
        assert s.index is rs.index
        assert s.dtype == rs.dtype
        assert s.name == rs.name

        # index but no data
        s = Series(index=[1, 2, 3])
        rs = s.apply(lambda x: x)
        tm.assert_series_equal(s, rs) 
Example #3
Source File: workspace.py    From pyGSTi with Apache License 2.0 6 votes vote down vote up
def add_unswitched(self, varname, value):
        """
        Adds a new non-switched-value to this Switchboard.

        This can be convenient for attaching related non-switched data to
        a :class:`Switchboard`.

        Parameters
        ----------
        varname : str
            A name for the variable being added.  This name will be used to
            access the new variable (as either a dictionary key or as an
            object member).

        value : object
            The un-switched value to associate with `varname`.

        Returns
        -------
        None
        """
        super(Switchboard, self).__setitem__(varname, value) 
Example #4
Source File: test_algos.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_same_object_is_in(self):
        # GH 22160
        # there could be special treatment for nans
        # the user however could define a custom class
        # with similar behavior, then we at least should
        # fall back to usual python's behavior: "a in [a] == True"
        class LikeNan(object):
            def __eq__(self):
                return False

            def __hash__(self):
                return 0

        a, b = LikeNan(), LikeNan()
        # same object -> True
        tm.assert_numpy_array_equal(algos.isin([a], [a]), np.array([True]))
        # different objects -> False
        tm.assert_numpy_array_equal(algos.isin([a], [b]), np.array([False])) 
Example #5
Source File: workspace.py    From pyGSTi with Apache License 2.0 6 votes vote down vote up
def render(self, typ="html"):
        """
        Render this Switchboard into the requested format.

        The returned string(s) are intended to be used to embedded a
        visualization of this object within a larger document.

        Parameters
        ----------
        typ : {"html"}
            The format to render as.  Currently only HTML is supported.

        Returns
        -------
        dict
            A dictionary of strings whose keys indicate which portion of
            the embeddable output the value is.  Keys will vary for different
            `typ`.  For `"html"`, keys are `"html"` and `"js"` for HTML and
            and Javascript code, respectively.
        """
        return self._render_base(typ, None, self.show) 
Example #6
Source File: workspace.py    From pyGSTi with Apache License 2.0 6 votes vote down vote up
def render(self, typ="html"):
        """
        Renders this object into the specifed format, specifically for
        embedding it within a larger document.

        Parameters
        ----------
        typ : str
            The format to render as.  Currently `"html"` is widely supported
            and `"latex"` is supported for tables.

        Returns
        -------
        dict
            A dictionary of strings whose keys indicate which portion of
            the embeddable output the value is.  Keys will vary for different
            `typ`.  For `"html"`, keys are `"html"` and `"js"` for HTML and
            and Javascript code, respectively.
        """
        raise NotImplementedError("Derived classes must implement their own render()") 
Example #7
Source File: workspace.py    From pyGSTi with Apache License 2.0 6 votes vote down vote up
def load_cache(self, cachefile):
        """
        Load this Workspace's cache from `cachefile`.

        Parameters
        ----------
        cachefile : str
            The filename to load the cache from.

        Returns
        -------
        None
        """
        with open(cachefile, 'rb') as infile:
            enable_plotly_pickling()
            oldCache = _pickle.load(infile).cache
            disable_plotly_pickling()
            for v in oldCache.values():
                if isinstance(v, WorkspaceOutput):  # hasattr(v,'ws') == True for plotly dicts (why?)
                    print('Updated {} object to set ws to self'.format(type(v)))
                    v.ws = self
            self.smartCache.cache.update(oldCache) 
Example #8
Source File: test_period.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_values(self):
        idx = pd.PeriodIndex([], freq='M')

        exp = np.array([], dtype=np.object)
        tm.assert_numpy_array_equal(idx.values, exp)
        tm.assert_numpy_array_equal(idx.get_values(), exp)
        exp = np.array([], dtype=np.int64)
        tm.assert_numpy_array_equal(idx._ndarray_values, exp)

        idx = pd.PeriodIndex(['2011-01', pd.NaT], freq='M')

        exp = np.array([pd.Period('2011-01', freq='M'), pd.NaT], dtype=object)
        tm.assert_numpy_array_equal(idx.values, exp)
        tm.assert_numpy_array_equal(idx.get_values(), exp)
        exp = np.array([492, -9223372036854775808], dtype=np.int64)
        tm.assert_numpy_array_equal(idx._ndarray_values, exp)

        idx = pd.PeriodIndex(['2011-01-01', pd.NaT], freq='D')

        exp = np.array([pd.Period('2011-01-01', freq='D'), pd.NaT],
                       dtype=object)
        tm.assert_numpy_array_equal(idx.values, exp)
        tm.assert_numpy_array_equal(idx.get_values(), exp)
        exp = np.array([14975, -9223372036854775808], dtype=np.int64)
        tm.assert_numpy_array_equal(idx._ndarray_values, exp) 
Example #9
Source File: mixed_variable_operator.py    From pymoo with Apache License 2.0 6 votes vote down vote up
def _do(self, problem, X, **kwargs):

        _, n_matings, n_var = X.shape

        def fun(mask, operator):
            return operator._do(problem, X[..., mask], **kwargs)

        ret = apply_mixed_variable_operation(problem, self.process, fun)

        # for the crossover the concatenation is different through the 3d arrays.
        X = np.full((self.n_offsprings, n_matings, n_var), np.nan, dtype=np.object)
        for i in range(len(self.process)):
            mask, _X = self.process[i]["mask"], ret[i]
            X[..., mask] = _X

        return X 
Example #10
Source File: test_algos.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_value_counts_datetime_outofbounds(self):
        # GH 13663
        s = Series([datetime(3000, 1, 1), datetime(5000, 1, 1),
                    datetime(5000, 1, 1), datetime(6000, 1, 1),
                    datetime(3000, 1, 1), datetime(3000, 1, 1)])
        res = s.value_counts()

        exp_index = Index([datetime(3000, 1, 1), datetime(5000, 1, 1),
                           datetime(6000, 1, 1)], dtype=object)
        exp = Series([3, 2, 1], index=exp_index)
        tm.assert_series_equal(res, exp)

        # GH 12424
        res = pd.to_datetime(Series(['2362-01-01', np.nan]),
                             errors='ignore')
        exp = Series(['2362-01-01', np.nan], dtype=object)
        tm.assert_series_equal(res, exp) 
Example #11
Source File: test_base.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_copy_name(self):
        # Check that "name" argument passed at initialization is honoured
        # GH12309
        index = self.create_index()

        first = index.__class__(index, copy=True, name='mario')
        second = first.__class__(first, copy=False)

        # Even though "copy=False", we want a new object.
        assert first is not second
        tm.assert_index_equal(first, second)

        assert first.name == 'mario'
        assert second.name == 'mario'

        s1 = Series(2, index=first)
        s2 = Series(3, index=second[:-1])

        s3 = s1 * s2

        assert s3.index.name == 'mario' 
Example #12
Source File: workspace.py    From pyGSTi with Apache License 2.0 6 votes vote down vote up
def add(self, varname, dependencies):
        """
        Adds a new switched-value to this Switchboard.

        Parameters
        ----------
        varname : str
            A name for the variable being added.  This name will be used to
            access the new variable (as either a dictionary key or as an
            object member).

        dependencies : list or tuple
            The (0-based) switch-indices specifying which switch positions
            the new variable is dependent on.  For example, if the Switchboard
            has two switches, one for "amplitude" and one for "frequency", and
            this value is only dependent on frequency, then `dependencies`
            should be set to `(1,)` or `[1]`.

        Returns
        -------
        None
        """
        super(Switchboard, self).__setitem__(varname, SwitchValue(self, varname, dependencies)) 
Example #13
Source File: test_coercion.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_insert_index_datetimes(self, fill_val, exp_dtype):
        obj = pd.DatetimeIndex(['2011-01-01', '2011-01-02', '2011-01-03',
                                '2011-01-04'], tz=fill_val.tz)
        assert obj.dtype == exp_dtype

        exp = pd.DatetimeIndex(['2011-01-01', fill_val.date(), '2011-01-02',
                                '2011-01-03', '2011-01-04'], tz=fill_val.tz)
        self._assert_insert_conversion(obj, fill_val, exp, exp_dtype)

        msg = "Passed item and index have different timezone"
        if fill_val.tz:
            with pytest.raises(ValueError, match=msg):
                obj.insert(1, pd.Timestamp('2012-01-01'))

        with pytest.raises(ValueError, match=msg):
            obj.insert(1, pd.Timestamp('2012-01-01', tz='Asia/Tokyo'))

        msg = "cannot insert DatetimeIndex with incompatible label"
        with pytest.raises(TypeError, match=msg):
            obj.insert(1, 1)

        pytest.xfail("ToDo: must coerce to object") 
Example #14
Source File: test_algos.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_first_nan_kept(self):
        # GH 22295
        # create different nans from bit-patterns:
        bits_for_nan1 = 0xfff8000000000001
        bits_for_nan2 = 0x7ff8000000000001
        NAN1 = struct.unpack("d", struct.pack("=Q", bits_for_nan1))[0]
        NAN2 = struct.unpack("d", struct.pack("=Q", bits_for_nan2))[0]
        assert NAN1 != NAN1
        assert NAN2 != NAN2
        for el_type in [np.float64, np.object]:
            a = np.array([NAN1, NAN2], dtype=el_type)
            result = pd.unique(a)
            assert result.size == 1
            # use bit patterns to identify which nan was kept:
            result_nan_bits = struct.unpack("=Q",
                                            struct.pack("d", result[0]))[0]
            assert result_nan_bits == bits_for_nan1 
Example #15
Source File: test_analytics.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_nsmallest_nlargest(self, s_main_dtypes_split):
        # float, int, datetime64 (use i8), timedelts64 (same),
        # object that are numbers, object that are strings
        s = s_main_dtypes_split

        assert_series_equal(s.nsmallest(2), s.iloc[[2, 1]])
        assert_series_equal(s.nsmallest(2, keep='last'), s.iloc[[2, 3]])

        empty = s.iloc[0:0]
        assert_series_equal(s.nsmallest(0), empty)
        assert_series_equal(s.nsmallest(-1), empty)
        assert_series_equal(s.nlargest(0), empty)
        assert_series_equal(s.nlargest(-1), empty)

        assert_series_equal(s.nsmallest(len(s)), s.sort_values())
        assert_series_equal(s.nsmallest(len(s) + 1), s.sort_values())
        assert_series_equal(s.nlargest(len(s)), s.iloc[[4, 0, 1, 3, 2]])
        assert_series_equal(s.nlargest(len(s) + 1),
                            s.iloc[[4, 0, 1, 3, 2]]) 
Example #16
Source File: test_analytics.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_value_counts(self):
        # GH 12835
        cats = Categorical(list('abcccb'), categories=list('cabd'))
        s = Series(cats, name='xxx')
        res = s.value_counts(sort=False)

        exp_index = CategoricalIndex(list('cabd'), categories=cats.categories)
        exp = Series([3, 1, 2, 0], name='xxx', index=exp_index)
        tm.assert_series_equal(res, exp)

        res = s.value_counts(sort=True)

        exp_index = CategoricalIndex(list('cbad'), categories=cats.categories)
        exp = Series([3, 2, 1, 0], name='xxx', index=exp_index)
        tm.assert_series_equal(res, exp)

        # check object dtype handles the Series.name as the same
        # (tested in test_base.py)
        s = Series(["a", "b", "c", "c", "c", "b"], name='xxx')
        res = s.value_counts()
        exp = Series([3, 2, 1], name='xxx', index=["c", "b", "a"])
        tm.assert_series_equal(res, exp) 
Example #17
Source File: test_coercion.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_where_index_datetimetz(self):
        fill_val = pd.Timestamp('2012-01-01', tz='US/Eastern')
        exp_dtype = np.object
        obj = pd.Index([pd.Timestamp('2011-01-01'),
                        pd.Timestamp('2011-01-02'),
                        pd.Timestamp('2011-01-03'),
                        pd.Timestamp('2011-01-04')])
        assert obj.dtype == 'datetime64[ns]'
        cond = pd.Index([True, False, True, False])

        msg = ("Index\\(\\.\\.\\.\\) must be called with a collection "
               "of some kind")
        with pytest.raises(TypeError, match=msg):
            obj.where(cond, fill_val)

        values = pd.Index(pd.date_range(fill_val, periods=4))
        exp = pd.Index([pd.Timestamp('2011-01-01'),
                        pd.Timestamp('2012-01-02', tz='US/Eastern'),
                        pd.Timestamp('2011-01-03'),
                        pd.Timestamp('2012-01-04', tz='US/Eastern')],
                       dtype=exp_dtype)

        self._assert_where_conversion(obj, cond, values, exp, exp_dtype) 
Example #18
Source File: test_coercion.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_where_object(self, klass, fill_val, exp_dtype):
        obj = klass(list('abcd'))
        assert obj.dtype == np.object
        cond = klass([True, False, True, False])

        if fill_val is True and klass is pd.Series:
            ret_val = 1
        else:
            ret_val = fill_val

        exp = klass(['a', ret_val, 'c', ret_val])
        self._assert_where_conversion(obj, cond, fill_val, exp, exp_dtype)

        if fill_val is True:
            values = klass([True, False, True, True])
        else:
            values = klass(fill_val * x for x in [5, 6, 7, 8])

        exp = klass(['a', values[1], 'c', values[3]])
        self._assert_where_conversion(obj, cond, values, exp, exp_dtype) 
Example #19
Source File: test_array.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_constructor_object_dtype(self):
        # GH 11856
        arr = SparseArray(['A', 'A', np.nan, 'B'], dtype=np.object)
        assert arr.dtype == SparseDtype(np.object)
        assert np.isnan(arr.fill_value)

        arr = SparseArray(['A', 'A', np.nan, 'B'], dtype=np.object,
                          fill_value='A')
        assert arr.dtype == SparseDtype(np.object, 'A')
        assert arr.fill_value == 'A'

        # GH 17574
        data = [False, 0, 100.0, 0.0]
        arr = SparseArray(data, dtype=np.object, fill_value=False)
        assert arr.dtype == SparseDtype(np.object, False)
        assert arr.fill_value is False
        arr_expected = np.array(data, dtype=np.object)
        it = (type(x) == type(y) and x == y for x, y in zip(arr, arr_expected))
        assert np.fromiter(it, dtype=np.bool).all() 
Example #20
Source File: test_base.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_constructor_from_index_dtlike(self, cast_as_obj, index):
        if cast_as_obj:
            result = pd.Index(index.astype(object))
        else:
            result = pd.Index(index)

        tm.assert_index_equal(result, index)

        if isinstance(index, pd.DatetimeIndex):
            assert result.tz == index.tz
            if cast_as_obj:
                # GH#23524 check that Index(dti, dtype=object) does not
                #  incorrectly raise ValueError, and that nanoseconds are not
                #  dropped
                index += pd.Timedelta(nanoseconds=50)
                result = pd.Index(index, dtype=object)
                assert result.dtype == np.object_
                assert list(result) == list(index) 
Example #21
Source File: test_base.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_constructor_from_frame_series_freq(self):
        # GH 6273
        # create from a series, passing a freq
        dts = ['1-1-1990', '2-1-1990', '3-1-1990', '4-1-1990', '5-1-1990']
        expected = DatetimeIndex(dts, freq='MS')

        df = pd.DataFrame(np.random.rand(5, 3))
        df['date'] = dts
        result = DatetimeIndex(df['date'], freq='MS')

        assert df['date'].dtype == object
        expected.name = 'date'
        tm.assert_index_equal(result, expected)

        expected = pd.Series(dts, name='date')
        tm.assert_series_equal(df['date'], expected)

        # GH 6274
        # infer freq of same
        freq = pd.infer_freq(df['date'])
        assert freq == 'MS' 
Example #22
Source File: workspace.py    From pyGSTi with Apache License 2.0 6 votes vote down vote up
def __init__(self, ws, fn, *args):
        """
        Create a new WorkspaceText object.  Usually not called directly.

        Parameters
        ----------
        ws : Workspace
            The workspace containing the new object.

        fn : function
            A text-creating function.

        args : various
            The arguments to `fn`.
        """
        super(WorkspaceText, self).__init__(ws)
        self.textfn = fn
        self.initargs = args
        self.texts, self.switchboards, self.sbSwitchIndices, self.switchpos_map = \
            self.ws.switchedCompute(self.textfn, *self.initargs) 
Example #23
Source File: workspace.py    From pyGSTi with Apache License 2.0 6 votes vote down vote up
def __init__(self, ws, fn, *args):
        """
        Create a new WorkspaceTable.  Usually not called directly.

        Parameters
        ----------
        ws : Workspace
            The workspace containing the new object.

        fn : function
            A table-creating function.

        args : various
            The arguments to `fn`.
        """
        super(WorkspaceTable, self).__init__(ws)
        self.tablefn = fn
        self.initargs = args
        self.tables, self.switchboards, self.sbSwitchIndices, self.switchpos_map = \
            self.ws.switchedCompute(self.tablefn, *self.initargs) 
Example #24
Source File: test_coercion.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_setitem_index_object(self, val, exp_dtype):
        obj = pd.Series([1, 2, 3, 4], index=list('abcd'))
        assert obj.index.dtype == np.object

        if exp_dtype is IndexError:
            temp = obj.copy()
            with pytest.raises(exp_dtype):
                temp[5] = 5
        else:
            exp_index = pd.Index(list('abcd') + [val])
            self._assert_setitem_index_conversion(obj, val, exp_index,
                                                  exp_dtype) 
Example #25
Source File: test_coercion.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_fillna_object(self, klass, fill_val, fill_dtype):
        obj = klass(['a', np.nan, 'c', 'd'])
        assert obj.dtype == np.object

        exp = klass(['a', fill_val, 'c', 'd'])
        self._assert_fillna_conversion(obj, fill_val, exp, fill_dtype) 
Example #26
Source File: test_base.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_intersect_str_dates(self):
        dt_dates = [datetime(2012, 2, 9), datetime(2012, 2, 22)]

        index1 = Index(dt_dates, dtype=object)
        index2 = Index(['aa'], dtype=object)
        result = index2.intersection(index1)

        expected = Index([], dtype=object)
        tm.assert_index_equal(result, expected) 
Example #27
Source File: test_base.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_deprecated_fastpath():

    with tm.assert_produces_warning(FutureWarning):
        idx = pd.Index(
            np.array(['a', 'b'], dtype=object), name='test', fastpath=True)

    expected = pd.Index(['a', 'b'], name='test')
    tm.assert_index_equal(idx, expected)

    with tm.assert_produces_warning(FutureWarning):
        idx = pd.Int64Index(
            np.array([1, 2, 3], dtype='int64'), name='test', fastpath=True)

    expected = pd.Index([1, 2, 3], name='test', dtype='int64')
    tm.assert_index_equal(idx, expected)

    with tm.assert_produces_warning(FutureWarning):
        idx = pd.RangeIndex(0, 5, 2, name='test', fastpath=True)

    expected = pd.RangeIndex(0, 5, 2, name='test')
    tm.assert_index_equal(idx, expected)

    with tm.assert_produces_warning(FutureWarning):
        idx = pd.CategoricalIndex(['a', 'b', 'c'], name='test', fastpath=True)

    expected = pd.CategoricalIndex(['a', 'b', 'c'], name='test')
    tm.assert_index_equal(idx, expected) 
Example #28
Source File: test_coercion.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_setitem_series_object(self, val, exp_dtype):
        obj = pd.Series(list('abcd'))
        assert obj.dtype == np.object

        exp = pd.Series(['a', val, 'c', 'd'])
        self._assert_setitem_series_conversion(obj, val, exp, exp_dtype) 
Example #29
Source File: test_algos.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_string_factorize(self, writable):
        data = np.array(['a', 'c', 'a', 'b', 'c'],
                        dtype=object)
        data.setflags(write=writable)
        exp_labels = np.array([0, 1, 0, 2, 1], dtype=np.intp)
        exp_uniques = np.array(['a', 'c', 'b'], dtype=object)

        labels, uniques = algos.factorize(data)
        tm.assert_numpy_array_equal(labels, exp_labels)
        tm.assert_numpy_array_equal(uniques, exp_uniques) 
Example #30
Source File: test_coercion.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_insert_index_object(self, insert, coerced_val, coerced_dtype):
        obj = pd.Index(list('abcd'))
        assert obj.dtype == np.object

        exp = pd.Index(['a', coerced_val, 'b', 'c', 'd'])
        self._assert_insert_conversion(obj, insert, exp, coerced_dtype)