Python numpy.bool_() Examples

The following are 30 code examples of numpy.bool_(). 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: test_panel.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_to_frame_mixed(self):
        panel = self.panel.fillna(0)
        panel['str'] = 'foo'
        panel['bool'] = panel['ItemA'] > 0

        lp = panel.to_frame()
        wp = lp.to_panel()
        assert wp['bool'].values.dtype == np.bool_
        # Previously, this was mutating the underlying
        # index and changing its name
        assert_frame_equal(wp['bool'], panel['bool'], check_names=False)

        # GH 8704
        # with categorical
        df = panel.to_frame()
        df['category'] = df['str'].astype('category')

        # to_panel
        # TODO: this converts back to object
        p = df.to_panel()
        expected = panel.copy()
        expected['category'] = 'foo'
        assert_panel_equal(p, expected) 
Example #2
Source File: test_inference.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_is_number(self):

        assert is_number(True)
        assert is_number(1)
        assert is_number(1.1)
        assert is_number(1 + 3j)
        assert is_number(np.bool(False))
        assert is_number(np.int64(1))
        assert is_number(np.float64(1.1))
        assert is_number(np.complex128(1 + 3j))
        assert is_number(np.nan)

        assert not is_number(None)
        assert not is_number('x')
        assert not is_number(datetime(2011, 1, 1))
        assert not is_number(np.datetime64('2011-01-01'))
        assert not is_number(Timestamp('2011-01-01'))
        assert not is_number(Timestamp('2011-01-01', tz='US/Eastern'))
        assert not is_number(timedelta(1000))
        assert not is_number(Timedelta('1 days'))

        # questionable
        assert not is_number(np.bool_(False))
        assert is_number(np.timedelta64(1, 'D')) 
Example #3
Source File: test_inference.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_bools(self):
        arr = np.array([True, False, True, True, True], dtype='O')
        result = lib.infer_dtype(arr, skipna=True)
        assert result == 'boolean'

        arr = np.array([np.bool_(True), np.bool_(False)], dtype='O')
        result = lib.infer_dtype(arr, skipna=True)
        assert result == 'boolean'

        arr = np.array([True, False, True, 'foo'], dtype='O')
        result = lib.infer_dtype(arr, skipna=True)
        assert result == 'mixed'

        arr = np.array([True, False, True], dtype=bool)
        result = lib.infer_dtype(arr, skipna=True)
        assert result == 'boolean'

        arr = np.array([True, np.nan, False], dtype='O')
        result = lib.infer_dtype(arr, skipna=True)
        assert result == 'boolean'

        result = lib.infer_dtype(arr, skipna=False)
        assert result == 'mixed' 
Example #4
Source File: test_arithmetic.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_flex_comparison_nat(self):
        # GH 15697, GH 22163 df.eq(pd.NaT) should behave like df == pd.NaT,
        # and _definitely_ not be NaN
        df = pd.DataFrame([pd.NaT])

        result = df == pd.NaT
        # result.iloc[0, 0] is a np.bool_ object
        assert result.iloc[0, 0].item() is False

        result = df.eq(pd.NaT)
        assert result.iloc[0, 0].item() is False

        result = df != pd.NaT
        assert result.iloc[0, 0].item() is True

        result = df.ne(pd.NaT)
        assert result.iloc[0, 0].item() is True 
Example #5
Source File: _dtype.py    From recruit with Apache License 2.0 6 votes vote down vote up
def _name_get(dtype):
    # provides dtype.name.__get__

    if dtype.isbuiltin == 2:
        # user dtypes don't promise to do anything special
        return dtype.type.__name__

    # Builtin classes are documented as returning a "bit name"
    name = dtype.type.__name__

    # handle bool_, str_, etc
    if name[-1] == '_':
        name = name[:-1]

    # append bit counts to str, unicode, and void
    if np.issubdtype(dtype, np.flexible) and not _isunsized(dtype):
        name += "{}".format(dtype.itemsize * 8)

    # append metadata to datetimes
    elif dtype.type in (np.datetime64, np.timedelta64):
        name += _datetime_metadata_str(dtype)

    return name 
Example #6
Source File: test_inference.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_is_bool(self):
        assert is_bool(True)
        assert is_bool(np.bool(False))
        assert is_bool(np.bool_(False))

        assert not is_bool(1)
        assert not is_bool(1.1)
        assert not is_bool(1 + 3j)
        assert not is_bool(np.int64(1))
        assert not is_bool(np.float64(1.1))
        assert not is_bool(np.complex128(1 + 3j))
        assert not is_bool(np.nan)
        assert not is_bool(None)
        assert not is_bool('x')
        assert not is_bool(datetime(2011, 1, 1))
        assert not is_bool(np.datetime64('2011-01-01'))
        assert not is_bool(Timestamp('2011-01-01'))
        assert not is_bool(Timestamp('2011-01-01', tz='US/Eastern'))
        assert not is_bool(timedelta(1000))
        assert not is_bool(np.timedelta64(1, 'D'))
        assert not is_bool(Timedelta('1 days')) 
Example #7
Source File: test_random.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_respect_dtype_singleton(self):
        # See gh-7203
        for dt in self.itype:
            lbnd = 0 if dt is np.bool_ else np.iinfo(dt).min
            ubnd = 2 if dt is np.bool_ else np.iinfo(dt).max + 1

            sample = self.rfunc(lbnd, ubnd, dtype=dt)
            assert_equal(sample.dtype, np.dtype(dt))

        for dt in (bool, int, np.long):
            lbnd = 0 if dt is bool else np.iinfo(dt).min
            ubnd = 2 if dt is bool else np.iinfo(dt).max + 1

            # gh-7284: Ensure that we get Python data types
            sample = self.rfunc(lbnd, ubnd, dtype=dt)
            assert_(not hasattr(sample, 'dtype'))
            assert_equal(type(sample), dt) 
Example #8
Source File: test_inference.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_is_integer(self):
        assert is_integer(1)
        assert is_integer(np.int64(1))

        assert not is_integer(True)
        assert not is_integer(1.1)
        assert not is_integer(1 + 3j)
        assert not is_integer(np.bool(False))
        assert not is_integer(np.bool_(False))
        assert not is_integer(np.float64(1.1))
        assert not is_integer(np.complex128(1 + 3j))
        assert not is_integer(np.nan)
        assert not is_integer(None)
        assert not is_integer('x')
        assert not is_integer(datetime(2011, 1, 1))
        assert not is_integer(np.datetime64('2011-01-01'))
        assert not is_integer(Timestamp('2011-01-01'))
        assert not is_integer(Timestamp('2011-01-01', tz='US/Eastern'))
        assert not is_integer(timedelta(1000))
        assert not is_integer(Timedelta('1 days'))

        # questionable
        assert is_integer(np.timedelta64(1, 'D')) 
Example #9
Source File: test_inference.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_is_float(self):
        assert is_float(1.1)
        assert is_float(np.float64(1.1))
        assert is_float(np.nan)

        assert not is_float(True)
        assert not is_float(1)
        assert not is_float(1 + 3j)
        assert not is_float(np.bool(False))
        assert not is_float(np.bool_(False))
        assert not is_float(np.int64(1))
        assert not is_float(np.complex128(1 + 3j))
        assert not is_float(None)
        assert not is_float('x')
        assert not is_float(datetime(2011, 1, 1))
        assert not is_float(np.datetime64('2011-01-01'))
        assert not is_float(Timestamp('2011-01-01'))
        assert not is_float(Timestamp('2011-01-01', tz='US/Eastern'))
        assert not is_float(timedelta(1000))
        assert not is_float(np.timedelta64(1, 'D'))
        assert not is_float(Timedelta('1 days')) 
Example #10
Source File: test_dtypes.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_select_dtypes_exclude_include_using_list_like(self):
        df = DataFrame({'a': list('abc'),
                        'b': list(range(1, 4)),
                        'c': np.arange(3, 6).astype('u1'),
                        'd': np.arange(4.0, 7.0, dtype='float64'),
                        'e': [True, False, True],
                        'f': pd.date_range('now', periods=3).values})
        exclude = np.datetime64,
        include = np.bool_, 'integer'
        r = df.select_dtypes(include=include, exclude=exclude)
        e = df[['b', 'c', 'e']]
        assert_frame_equal(r, e)

        exclude = 'datetime',
        include = 'bool', 'int64', 'int32'
        r = df.select_dtypes(include=include, exclude=exclude)
        e = df[['b', 'e']]
        assert_frame_equal(r, e) 
Example #11
Source File: test_core.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_allany(self):
        # Checks the any/all methods/functions.
        x = np.array([[0.13, 0.26, 0.90],
                      [0.28, 0.33, 0.63],
                      [0.31, 0.87, 0.70]])
        m = np.array([[True, False, False],
                      [False, False, False],
                      [True, True, False]], dtype=np.bool_)
        mx = masked_array(x, mask=m)
        mxbig = (mx > 0.5)
        mxsmall = (mx < 0.5)

        assert_(not mxbig.all())
        assert_(mxbig.any())
        assert_equal(mxbig.all(0), [False, False, True])
        assert_equal(mxbig.all(1), [False, False, True])
        assert_equal(mxbig.any(0), [False, False, True])
        assert_equal(mxbig.any(1), [True, True, True])

        assert_(not mxsmall.all())
        assert_(mxsmall.any())
        assert_equal(mxsmall.all(0), [True, True, False])
        assert_equal(mxsmall.all(1), [False, False, False])
        assert_equal(mxsmall.any(0), [True, True, False])
        assert_equal(mxsmall.any(1), [True, True, False]) 
Example #12
Source File: sparse.py    From recruit with Apache License 2.0 6 votes vote down vote up
def _wrap_result(name, data, sparse_index, fill_value, dtype=None):
    """
    wrap op result to have correct dtype
    """
    if name.startswith('__'):
        # e.g. __eq__ --> eq
        name = name[2:-2]

    if name in ('eq', 'ne', 'lt', 'gt', 'le', 'ge'):
        dtype = np.bool

    fill_value = lib.item_from_zerodim(fill_value)

    if is_bool_dtype(dtype):
        # fill_value may be np.bool_
        fill_value = bool(fill_value)
    return SparseArray(data,
                       sparse_index=sparse_index,
                       fill_value=fill_value,
                       dtype=dtype) 
Example #13
Source File: test_strings.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_contains_nan(self):
        # PR #14171
        s = Series([np.nan, np.nan, np.nan], dtype=np.object_)

        result = s.str.contains('foo', na=False)
        expected = Series([False, False, False], dtype=np.bool_)
        assert_series_equal(result, expected)

        result = s.str.contains('foo', na=True)
        expected = Series([True, True, True], dtype=np.bool_)
        assert_series_equal(result, expected)

        result = s.str.contains('foo', na="foo")
        expected = Series(["foo", "foo", "foo"], dtype=np.object_)
        assert_series_equal(result, expected)

        result = s.str.contains('foo')
        expected = Series([np.nan, np.nan, np.nan], dtype=np.object_)
        assert_series_equal(result, expected) 
Example #14
Source File: histograms.py    From recruit with Apache License 2.0 6 votes vote down vote up
def _ravel_and_check_weights(a, weights):
    """ Check a and weights have matching shapes, and ravel both """
    a = np.asarray(a)

    # Ensure that the array is a "subtractable" dtype
    if a.dtype == np.bool_:
        warnings.warn("Converting input from {} to {} for compatibility."
                      .format(a.dtype, np.uint8),
                      RuntimeWarning, stacklevel=2)
        a = a.astype(np.uint8)

    if weights is not None:
        weights = np.asarray(weights)
        if weights.shape != a.shape:
            raise ValueError(
                'weights should have the same shape as a.')
        weights = weights.ravel()
    a = a.ravel()
    return a, weights 
Example #15
Source File: test_masked_matrix.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_allany_onmatrices(self):
        x = np.array([[0.13, 0.26, 0.90],
                      [0.28, 0.33, 0.63],
                      [0.31, 0.87, 0.70]])
        X = np.matrix(x)
        m = np.array([[True, False, False],
                      [False, False, False],
                      [True, True, False]], dtype=np.bool_)
        mX = masked_array(X, mask=m)
        mXbig = (mX > 0.5)
        mXsmall = (mX < 0.5)

        assert_(not mXbig.all())
        assert_(mXbig.any())
        assert_equal(mXbig.all(0), np.matrix([False, False, True]))
        assert_equal(mXbig.all(1), np.matrix([False, False, True]).T)
        assert_equal(mXbig.any(0), np.matrix([False, False, True]))
        assert_equal(mXbig.any(1), np.matrix([True, True, True]).T)

        assert_(not mXsmall.all())
        assert_(mXsmall.any())
        assert_equal(mXsmall.all(0), np.matrix([True, True, False]))
        assert_equal(mXsmall.all(1), np.matrix([False, False, False]).T)
        assert_equal(mXsmall.any(0), np.matrix([True, True, False]))
        assert_equal(mXsmall.any(1), np.matrix([True, True, False]).T) 
Example #16
Source File: duplicate.py    From pymoo with Apache License 2.0 6 votes vote down vote up
def _do(self, pop, other, is_duplicate):

        def to_float(val):
            if isinstance(val, bool) or isinstance(val, np.bool_):
                return 0.0 if val else 1.0
            else:
                return val

        if other is None:
            for i in range(len(pop)):
                for j in range(i + 1, len(pop)):
                    val = to_float(self.cmp(pop[i], pop[j]))
                    if val < self.epsilon:
                        is_duplicate[i] = True
                        break
        else:
            for i in range(len(pop)):
                for j in range(len(other)):
                    val = to_float(self.cmp(pop[i], other[j]))
                    if val < self.epsilon:
                        is_duplicate[i] = True
                        break

        return is_duplicate 
Example #17
Source File: test_regression.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_ticket_1539(self):
        dtypes = [x for x in np.typeDict.values()
                  if (issubclass(x, np.number)
                      and not issubclass(x, np.timedelta64))]
        a = np.array([], np.bool_)  # not x[0] because it is unordered
        failures = []

        for x in dtypes:
            b = a.astype(x)
            for y in dtypes:
                c = a.astype(y)
                try:
                    np.dot(b, c)
                except TypeError:
                    failures.append((x, y))
        if failures:
            raise AssertionError("Failures: %r" % failures) 
Example #18
Source File: TargetList.py    From EXOSIMS with 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 #19
Source File: sparse.py    From recruit with Apache License 2.0 5 votes vote down vote up
def _create_comparison_method(cls, op):
        def cmp_method(self, other):
            op_name = op.__name__

            if op_name in {'and_', 'or_'}:
                op_name = op_name[:-1]

            if isinstance(other, (ABCSeries, ABCIndexClass)):
                # Rely on pandas to unbox and dispatch to us.
                return NotImplemented

            if not is_scalar(other) and not isinstance(other, type(self)):
                # convert list-like to ndarray
                other = np.asarray(other)

            if isinstance(other, np.ndarray):
                # TODO: make this more flexible than just ndarray...
                if len(self) != len(other):
                    raise AssertionError("length mismatch: {self} vs. {other}"
                                         .format(self=len(self),
                                                 other=len(other)))
                other = SparseArray(other, fill_value=self.fill_value)

            if isinstance(other, SparseArray):
                return _sparse_array_op(self, other, op, op_name)
            else:
                with np.errstate(all='ignore'):
                    fill_value = op(self.fill_value, other)
                    result = op(self.sp_values, other)

                return type(self)(result,
                                  sparse_index=self.sp_index,
                                  fill_value=fill_value,
                                  dtype=np.bool_)

        name = '__{name}__'.format(name=op.__name__)
        return compat.set_function_name(cmp_method, name, cls) 
Example #20
Source File: blocks.py    From recruit with Apache License 2.0 5 votes vote down vote up
def should_store(self, value):
        return not (issubclass(value.dtype.type,
                               (np.integer, np.floating, np.complexfloating,
                                np.datetime64, np.bool_)) or
                    # TODO(ExtensionArray): remove is_extension_type
                    # when all extension arrays have been ported.
                    is_extension_type(value) or
                    is_extension_array_dtype(value)) 
Example #21
Source File: base.py    From recruit with Apache License 2.0 5 votes vote down vote up
def _isnan(self):
        """
        Return if each value is NaN.
        """
        if self._can_hold_na:
            return isna(self)
        else:
            # shouldn't reach to this condition by checking hasnans beforehand
            values = np.empty(len(self), dtype=np.bool_)
            values.fill(False)
            return values 
Example #22
Source File: test_packers.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_list_mixed(self):
        x = [1.0, np.float32(3.5), np.complex128(4.25), u('foo'), np.bool_(1)]
        x_rec = self.encode_decode(x)
        # current msgpack cannot distinguish list/tuple
        tm.assert_almost_equal(tuple(x), x_rec)

        x_rec = self.encode_decode(tuple(x))
        tm.assert_almost_equal(tuple(x), x_rec) 
Example #23
Source File: blocks.py    From recruit with Apache License 2.0 5 votes vote down vote up
def _can_hold_element(self, element):
        tipo = maybe_infer_dtype_type(element)
        if tipo is not None:
            return issubclass(tipo.type, np.bool_)
        return isinstance(element, (bool, np.bool_)) 
Example #24
Source File: test_constructors.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_constructor_scalar_inference(self):
        data = {'int': 1, 'bool': True,
                'float': 3., 'complex': 4j, 'object': 'foo'}
        df = DataFrame(data, index=np.arange(10))

        assert df['int'].dtype == np.int64
        assert df['bool'].dtype == np.bool_
        assert df['float'].dtype == np.float64
        assert df['complex'].dtype == np.complex128
        assert df['object'].dtype == np.object_ 
Example #25
Source File: test_analytics.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_any_all_np_func(self, func, data, expected):
        # GH 19976
        data = DataFrame(data)
        result = func(data)
        assert isinstance(result, np.bool_)
        assert result.item() is expected

        # method version
        result = getattr(DataFrame(data), func.__name__)(axis=None)
        assert isinstance(result, np.bool_)
        assert result.item() is expected 
Example #26
Source File: test_operators.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_logical_operators(self):

        def _check_bin_op(op):
            result = op(df1, df2)
            expected = DataFrame(op(df1.values, df2.values), index=df1.index,
                                 columns=df1.columns)
            assert result.values.dtype == np.bool_
            assert_frame_equal(result, expected)

        def _check_unary_op(op):
            result = op(df1)
            expected = DataFrame(op(df1.values), index=df1.index,
                                 columns=df1.columns)
            assert result.values.dtype == np.bool_
            assert_frame_equal(result, expected)

        df1 = {'a': {'a': True, 'b': False, 'c': False, 'd': True, 'e': True},
               'b': {'a': False, 'b': True, 'c': False,
                     'd': False, 'e': False},
               'c': {'a': False, 'b': False, 'c': True,
                     'd': False, 'e': False},
               'd': {'a': True, 'b': False, 'c': False, 'd': True, 'e': True},
               'e': {'a': True, 'b': False, 'c': False, 'd': True, 'e': True}}

        df2 = {'a': {'a': True, 'b': False, 'c': True, 'd': False, 'e': False},
               'b': {'a': False, 'b': True, 'c': False,
                     'd': False, 'e': False},
               'c': {'a': True, 'b': False, 'c': True, 'd': False, 'e': False},
               'd': {'a': False, 'b': False, 'c': False,
                     'd': True, 'e': False},
               'e': {'a': False, 'b': False, 'c': False,
                     'd': False, 'e': True}}

        df1 = DataFrame(df1)
        df2 = DataFrame(df2)

        _check_bin_op(operator.and_)
        _check_bin_op(operator.or_)
        _check_bin_op(operator.xor)

        _check_unary_op(operator.inv)  # TODO: belongs elsewhere 
Example #27
Source File: test_indexing.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_lookup(self):
        def alt(df, rows, cols, dtype):
            with tm.assert_produces_warning(FutureWarning,
                                            check_stacklevel=False):
                result = [df.get_value(r, c) for r, c in zip(rows, cols)]
            return np.array(result, dtype=dtype)

        def testit(df):
            rows = list(df.index) * len(df.columns)
            cols = list(df.columns) * len(df.index)
            result = df.lookup(rows, cols)
            expected = alt(df, rows, cols, dtype=np.object_)
            tm.assert_almost_equal(result, expected, check_dtype=False)

        testit(self.mixed_frame)
        testit(self.frame)

        df = DataFrame({'label': ['a', 'b', 'a', 'c'],
                        'mask_a': [True, True, False, True],
                        'mask_b': [True, False, False, False],
                        'mask_c': [False, True, False, True]})
        df['mask'] = df.lookup(df.index, 'mask_' + df['label'])
        exp_mask = alt(df, df.index, 'mask_' + df['label'], dtype=np.bool_)
        tm.assert_series_equal(df['mask'], pd.Series(exp_mask, name='mask'))
        assert df['mask'].dtype == np.bool_

        with pytest.raises(KeyError):
            self.frame.lookup(['xyz'], ['A'])

        with pytest.raises(KeyError):
            self.frame.lookup([self.frame.index[0]], ['xyz'])

        with pytest.raises(ValueError, match='same size'):
            self.frame.lookup(['a', 'b', 'c'], ['a']) 
Example #28
Source File: test_algos.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_arrmap():
    values = np.array(['foo', 'foo', 'bar', 'bar', 'baz', 'qux'], dtype='O')
    result = libalgos.arrmap_object(values, lambda x: x in ['foo', 'bar'])
    assert (result.dtype == np.bool_) 
Example #29
Source File: test_internals.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_as_array_int_bool(self):
        mgr = create_mgr('a: bool-1; b: bool-2')
        assert mgr.as_array().dtype == np.bool_

        mgr = create_mgr('a: i8-1; b: i8-2; c: i4; d: i2; e: u1')
        assert mgr.as_array().dtype == np.int64

        mgr = create_mgr('c: i4; d: i2; e: u1')
        assert mgr.as_array().dtype == np.int32 
Example #30
Source File: test_panel.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_panel_np_all():
    wp = Panel({"A": DataFrame({'b': [1, 2]})})
    result = np.all(wp)
    assert result == np.bool_(True)