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: test_analytics.py From recruit with Apache License 2.0 | 6 votes |
def test_stat_operators_attempt_obj_array(self, method): # GH 676 data = { 'a': [-0.00049987540199591344, -0.0016467257772919831, 0.00067695870775883013], 'b': [-0, -0, 0.0], 'c': [0.00031111847529610595, 0.0014902627951905339, -0.00094099200035979691] } df1 = DataFrame(data, index=['foo', 'bar', 'baz'], dtype='O') df2 = DataFrame({0: [np.nan, 2], 1: [np.nan, 3], 2: [np.nan, 4]}, dtype=object) for df in [df1, df2]: assert df.values.dtype == np.object_ result = getattr(df, method)(1) expected = getattr(df.astype('f8'), method)(1) if method in ['sum', 'prod']: tm.assert_series_equal(result, expected)
Example #2
Source File: test_dtypes.py From recruit with Apache License 2.0 | 6 votes |
def test_astype_datetime(self): s = Series(iNaT, dtype='M8[ns]', index=lrange(5)) s = s.astype('O') assert s.dtype == np.object_ s = Series([datetime(2001, 1, 2, 0, 0)]) s = s.astype('O') assert s.dtype == np.object_ s = Series([datetime(2001, 1, 2, 0, 0) for i in range(3)]) s[1] = np.nan assert s.dtype == 'M8[ns]' s = s.astype('O') assert s.dtype == np.object_
Example #3
Source File: test_constructors.py From recruit with Apache License 2.0 | 6 votes |
def test_constructor_dict_cast(self): # cast float tests test_data = { 'A': {'1': 1, '2': 2}, 'B': {'1': '1', '2': '2', '3': '3'}, } frame = DataFrame(test_data, dtype=float) assert len(frame) == 3 assert frame['B'].dtype == np.float64 assert frame['A'].dtype == np.float64 frame = DataFrame(test_data) assert len(frame) == 3 assert frame['B'].dtype == np.object_ assert frame['A'].dtype == np.float64 # can't cast to float test_data = { 'A': dict(zip(range(20), tm.makeStringIndex(20))), 'B': dict(zip(range(15), np.random.randn(15))) } frame = DataFrame(test_data, dtype=float) assert len(frame) == 20 assert frame['A'].dtype == np.object_ assert frame['B'].dtype == np.float64
Example #4
Source File: test_constructors.py From recruit with Apache License 2.0 | 6 votes |
def test_fromDict(self): data = {'a': 0, 'b': 1, 'c': 2, 'd': 3} series = Series(data) assert tm.is_sorted(series.index) data = {'a': 0, 'b': '1', 'c': '2', 'd': datetime.now()} series = Series(data) assert series.dtype == np.object_ data = {'a': 0, 'b': '1', 'c': '2', 'd': '3'} series = Series(data) assert series.dtype == np.object_ data = {'a': '0', 'b': '1'} series = Series(data, dtype=float) assert series.dtype == np.float64
Example #5
Source File: test_constructors.py From recruit with Apache License 2.0 | 6 votes |
def test_fromValue(self, datetime_series): nans = Series(np.NaN, index=datetime_series.index) assert nans.dtype == np.float_ assert len(nans) == len(datetime_series) strings = Series('foo', index=datetime_series.index) assert strings.dtype == np.object_ assert len(strings) == len(datetime_series) d = datetime.now() dates = Series(d, index=datetime_series.index) assert dates.dtype == 'M8[ns]' assert len(dates) == len(datetime_series) # GH12336 # Test construction of categorical series from value categorical = Series(0, index=datetime_series.index, dtype="category") expected = Series(0, index=datetime_series.index).astype("category") assert categorical.dtype == 'category' assert len(categorical) == len(datetime_series) tm.assert_series_equal(categorical, expected)
Example #6
Source File: test_dtypes.py From recruit with Apache License 2.0 | 6 votes |
def test_is_dtype(self): assert PeriodDtype.is_dtype(self.dtype) assert PeriodDtype.is_dtype('period[D]') assert PeriodDtype.is_dtype('period[3D]') assert PeriodDtype.is_dtype(PeriodDtype('3D')) assert PeriodDtype.is_dtype('period[U]') assert PeriodDtype.is_dtype('period[S]') assert PeriodDtype.is_dtype(PeriodDtype('U')) assert PeriodDtype.is_dtype(PeriodDtype('S')) assert not PeriodDtype.is_dtype('D') assert not PeriodDtype.is_dtype('3D') assert not PeriodDtype.is_dtype('U') assert not PeriodDtype.is_dtype('S') assert not PeriodDtype.is_dtype('foo') assert not PeriodDtype.is_dtype(np.object_) assert not PeriodDtype.is_dtype(np.int64) assert not PeriodDtype.is_dtype(np.float64)
Example #7
Source File: test_dtypes.py From recruit with Apache License 2.0 | 6 votes |
def test_is_dtype(self): assert IntervalDtype.is_dtype(self.dtype) assert IntervalDtype.is_dtype('interval') assert IntervalDtype.is_dtype(IntervalDtype('float64')) assert IntervalDtype.is_dtype(IntervalDtype('int64')) assert IntervalDtype.is_dtype(IntervalDtype(np.int64)) assert not IntervalDtype.is_dtype('D') assert not IntervalDtype.is_dtype('3D') assert not IntervalDtype.is_dtype('U') assert not IntervalDtype.is_dtype('S') assert not IntervalDtype.is_dtype('foo') assert not IntervalDtype.is_dtype('IntervalA') assert not IntervalDtype.is_dtype(np.object_) assert not IntervalDtype.is_dtype(np.int64) assert not IntervalDtype.is_dtype(np.float64)
Example #8
Source File: test_base.py From recruit with Apache License 2.0 | 6 votes |
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 #9
Source File: test_strings.py From recruit with Apache License 2.0 | 6 votes |
def test_zfill(self): values = Series(['1', '22', 'aaa', '333', '45678']) result = values.str.zfill(5) expected = Series(['00001', '00022', '00aaa', '00333', '45678']) tm.assert_series_equal(result, expected) expected = np.array([v.zfill(5) for v in values.values], dtype=np.object_) tm.assert_numpy_array_equal(result.values, expected) result = values.str.zfill(3) expected = Series(['001', '022', 'aaa', '333', '45678']) tm.assert_series_equal(result, expected) expected = np.array([v.zfill(3) for v in values.values], dtype=np.object_) tm.assert_numpy_array_equal(result.values, expected) values = Series(['1', np.nan, 'aaa', np.nan, '45678']) result = values.str.zfill(5) expected = Series(['00001', np.nan, '00aaa', np.nan, '45678']) tm.assert_series_equal(result, expected)
Example #10
Source File: test_groupby.py From recruit with Apache License 2.0 | 6 votes |
def test_convert_objects_leave_decimal_alone(): s = Series(lrange(5)) labels = np.array(['a', 'b', 'c', 'd', 'e'], dtype='O') def convert_fast(x): return Decimal(str(x.mean())) def convert_force_pure(x): # base will be length 0 assert (len(x.values.base) > 0) return Decimal(str(x.mean())) grouped = s.groupby(labels) result = grouped.agg(convert_fast) assert result.dtype == np.object_ assert isinstance(result[0], Decimal) result = grouped.agg(convert_force_pure) assert result.dtype == np.object_ assert isinstance(result[0], Decimal)
Example #11
Source File: test_regression.py From recruit with Apache License 2.0 | 6 votes |
def test_object_array_refcount_self_assign(self): # Ticket #711 class VictimObject(object): deleted = False def __del__(self): self.deleted = True d = VictimObject() arr = np.zeros(5, dtype=np.object_) arr[:] = d del d arr[:] = arr # refcount of 'd' might hit zero here assert_(not arr[0].deleted) arr[:] = arr # trying to induce a segfault by doing it again... assert_(not arr[0].deleted)
Example #12
Source File: test_textreader.py From recruit with Apache License 2.0 | 5 votes |
def test_embedded_newline(self): data = 'a\n"hello\nthere"\nthis' reader = TextReader(StringIO(data), header=None) result = reader.read() expected = np.array(['a', 'hello\nthere', 'this'], dtype=np.object_) tm.assert_numpy_array_equal(result[0], expected)
Example #13
Source File: test_dtypes.py From recruit with Apache License 2.0 | 5 votes |
def test_basic_dtype(self): assert is_interval_dtype('interval[int64]') assert is_interval_dtype(IntervalIndex.from_tuples([(0, 1)])) assert is_interval_dtype(IntervalIndex.from_breaks(np.arange(4))) assert is_interval_dtype(IntervalIndex.from_breaks( date_range('20130101', periods=3))) assert not is_interval_dtype('U') assert not is_interval_dtype('S') assert not is_interval_dtype('foo') assert not is_interval_dtype(np.object_) assert not is_interval_dtype(np.int64) assert not is_interval_dtype(np.float64)
Example #14
Source File: core.py From esmlab with Apache License 2.0 | 5 votes |
def isdecoded(self, obj): return obj.dtype.type in {np.str_, np.object_, np.datetime64}
Example #15
Source File: strings.py From recruit with Apache License 2.0 | 5 votes |
def _validate(data): from pandas.core.index import Index if (isinstance(data, ABCSeries) and not ((is_categorical_dtype(data.dtype) and is_object_dtype(data.values.categories)) or (is_object_dtype(data.dtype)))): # it's neither a string series not a categorical series with # strings inside the categories. # this really should exclude all series with any non-string values # (instead of test for object dtype), but that isn't practical for # performance reasons until we have a str dtype (GH 9343) raise AttributeError("Can only use .str accessor with string " "values, which use np.object_ dtype in " "pandas") elif isinstance(data, Index): # can't use ABCIndex to exclude non-str # see src/inference.pyx which can contain string values allowed_types = ('string', 'unicode', 'mixed', 'mixed-integer') if is_categorical_dtype(data.dtype): inf_type = data.categories.inferred_type else: inf_type = data.inferred_type if inf_type not in allowed_types: message = ("Can only use .str accessor with string values " "(i.e. inferred_type is 'string', 'unicode' or " "'mixed')") raise AttributeError(message) if data.nlevels > 1: message = ("Can only use .str accessor with Index, not " "MultiIndex") raise AttributeError(message)
Example #16
Source File: cast.py From recruit with Apache License 2.0 | 5 votes |
def maybe_cast_item(obj, item, dtype): chunk = obj[item] if chunk.values.dtype != dtype: if dtype in (np.object_, np.bool_): obj[item] = chunk.astype(np.object_) elif not issubclass(dtype, (np.integer, np.bool_)): # pragma: no cover raise ValueError("Unexpected dtype encountered: {dtype}" .format(dtype=dtype))
Example #17
Source File: cast.py From recruit with Apache License 2.0 | 5 votes |
def maybe_convert_platform(values): """ try to do platform conversion, allow ndarray or list here """ if isinstance(values, (list, tuple)): values = construct_1d_object_array_from_listlike(list(values)) if getattr(values, 'dtype', None) == np.object_: if hasattr(values, '_values'): values = values._values values = lib.maybe_convert_objects(values) return values
Example #18
Source File: ops.py From recruit with Apache License 2.0 | 5 votes |
def _comp_method_OBJECT_ARRAY(op, x, y): if isinstance(y, list): y = construct_1d_object_array_from_listlike(y) if isinstance(y, (np.ndarray, ABCSeries, ABCIndex)): if not is_object_dtype(y.dtype): y = y.astype(np.object_) if isinstance(y, (ABCSeries, ABCIndex)): y = y.values result = libops.vec_compare(x, y, op) else: result = libops.scalar_compare(x, y, op) return result
Example #19
Source File: timedeltas.py From recruit with Apache License 2.0 | 5 votes |
def objects_to_td64ns(data, unit="ns", errors="raise"): """ Convert a object-dtyped or string-dtyped array into an timedelta64[ns]-dtyped array. Parameters ---------- data : ndarray or Index unit : str, default "ns" The timedelta unit to treat integers as multiples of. errors : {"raise", "coerce", "ignore"}, default "raise" How to handle elements that cannot be converted to timedelta64[ns]. See ``pandas.to_timedelta`` for details. Returns ------- numpy.ndarray : timedelta64[ns] array converted from data Raises ------ ValueError : Data cannot be converted to timedelta64[ns]. Notes ----- Unlike `pandas.to_timedelta`, if setting `errors=ignore` will not cause errors to be ignored; they are caught and subsequently ignored at a higher level. """ # coerce Index to np.ndarray, converting string-dtype if necessary values = np.array(data, dtype=np.object_, copy=False) result = array_to_timedelta64(values, unit=unit, errors=errors) return result.view('timedelta64[ns]')
Example #20
Source File: construction.py From recruit with Apache License 2.0 | 5 votes |
def _list_of_series_to_arrays(data, columns, coerce_float=False, dtype=None): if columns is None: columns = _get_objs_combined_axis(data, sort=False) indexer_cache = {} aligned_values = [] for s in data: index = getattr(s, 'index', None) if index is None: index = ibase.default_index(len(s)) if id(index) in indexer_cache: indexer = indexer_cache[id(index)] else: indexer = indexer_cache[id(index)] = index.get_indexer(columns) values = com.values_from_object(s) aligned_values.append(algorithms.take_1d(values, indexer)) values = np.vstack(aligned_values) if values.dtype == np.object_: content = list(values.T) return _convert_object_array(content, columns, dtype=dtype, coerce_float=coerce_float) else: return values.T, columns
Example #21
Source File: test_apply.py From recruit with Apache License 2.0 | 5 votes |
def test_map_decimal(self, string_series): from decimal import Decimal result = string_series.map(lambda x: Decimal(str(x))) assert result.dtype == np.object_ assert isinstance(result[0], Decimal)
Example #22
Source File: test_indexing.py From recruit with Apache License 2.0 | 5 votes |
def test_xs(self): idx = self.frame.index[5] xs = self.frame.xs(idx) for item, value in compat.iteritems(xs): if np.isnan(value): assert np.isnan(self.frame[item][idx]) else: assert value == self.frame[item][idx] # mixed-type xs test_data = { 'A': {'1': 1, '2': 2}, 'B': {'1': '1', '2': '2', '3': '3'}, } frame = DataFrame(test_data) xs = frame.xs('1') assert xs.dtype == np.object_ assert xs['A'] == 1 assert xs['B'] == '1' with pytest.raises(KeyError): self.tsframe.xs(self.tsframe.index[0] - BDay()) # xs get column series = self.frame.xs('A', axis=1) expected = self.frame['A'] assert_series_equal(series, expected) # view is returned if possible series = self.frame.xs('A', axis=1) series[:] = 5 assert (expected == 5).all()
Example #23
Source File: test_indexing.py From recruit with Apache License 2.0 | 5 votes |
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 #24
Source File: test_axis_select_reindex.py From recruit with Apache License 2.0 | 5 votes |
def test_reindex_boolean(self): frame = DataFrame(np.ones((10, 2), dtype=bool), index=np.arange(0, 20, 2), columns=[0, 2]) reindexed = frame.reindex(np.arange(10)) assert reindexed.values.dtype == np.object_ assert isna(reindexed[0][1]) reindexed = frame.reindex(columns=lrange(3)) assert reindexed.values.dtype == np.object_ assert isna(reindexed[1]).all()
Example #25
Source File: test_strings.py From recruit with Apache License 2.0 | 5 votes |
def test_endswith(self): values = Series(['om', NA, 'foo_nom', 'nom', 'bar_foo', NA, 'foo']) result = values.str.endswith('foo') exp = Series([False, NA, False, False, True, NA, True]) tm.assert_series_equal(result, exp) # mixed mixed = ['a', NA, 'b', True, datetime.today(), 'foo', None, 1, 2.] rs = strings.str_endswith(mixed, 'f') xp = np.array([False, NA, False, NA, NA, False, NA, NA, NA], dtype=np.object_) tm.assert_numpy_array_equal(rs, xp) rs = Series(mixed).str.endswith('f') xp = Series([False, NA, False, NA, NA, False, NA, NA, NA]) assert isinstance(rs, Series) tm.assert_series_equal(rs, xp) # unicode values = Series([u('om'), NA, u('foo_nom'), u('nom'), u('bar_foo'), NA, u('foo')]) result = values.str.endswith('foo') exp = Series([False, NA, False, False, True, NA, True]) tm.assert_series_equal(result, exp) result = values.str.endswith('foo', na=False) tm.assert_series_equal(result, exp.fillna(False).astype(bool))
Example #26
Source File: test_strings.py From recruit with Apache License 2.0 | 5 votes |
def test_startswith(self): values = Series(['om', NA, 'foo_nom', 'nom', 'bar_foo', NA, 'foo']) result = values.str.startswith('foo') exp = Series([False, NA, True, False, False, NA, True]) tm.assert_series_equal(result, exp) # mixed mixed = np.array(['a', NA, 'b', True, datetime.today(), 'foo', None, 1, 2.], dtype=np.object_) rs = strings.str_startswith(mixed, 'f') xp = np.array([False, NA, False, NA, NA, True, NA, NA, NA], dtype=np.object_) tm.assert_numpy_array_equal(rs, xp) rs = Series(mixed).str.startswith('f') assert isinstance(rs, Series) xp = Series([False, NA, False, NA, NA, True, NA, NA, NA]) tm.assert_series_equal(rs, xp) # unicode values = Series([u('om'), NA, u('foo_nom'), u('nom'), u('bar_foo'), NA, u('foo')]) result = values.str.startswith('foo') exp = Series([False, NA, True, False, False, NA, True]) tm.assert_series_equal(result, exp) result = values.str.startswith('foo', na=True) tm.assert_series_equal(result, exp.fillna(True).astype(bool))
Example #27
Source File: test_constructors.py From recruit with Apache License 2.0 | 5 votes |
def test_constructor_pass_none(self): s = Series(None, index=lrange(5)) assert s.dtype == np.float64 s = Series(None, index=lrange(5), dtype=object) assert s.dtype == np.object_ # GH 7431 # inference on the index s = Series(index=np.array([None])) expected = Series(index=Index([None])) assert_series_equal(s, expected)
Example #28
Source File: test_constructors.py From recruit with Apache License 2.0 | 5 votes |
def test_categorical_sideeffects_free(self): # Passing a categorical to a Series and then changing values in either # the series or the categorical should not change the values in the # other one, IF you specify copy! cat = Categorical(["a", "b", "c", "a"]) s = Series(cat, copy=True) assert s.cat is not cat s.cat.categories = [1, 2, 3] exp_s = np.array([1, 2, 3, 1], dtype=np.int64) exp_cat = np.array(["a", "b", "c", "a"], dtype=np.object_) tm.assert_numpy_array_equal(s.__array__(), exp_s) tm.assert_numpy_array_equal(cat.__array__(), exp_cat) # setting s[0] = 2 exp_s2 = np.array([2, 2, 3, 1], dtype=np.int64) tm.assert_numpy_array_equal(s.__array__(), exp_s2) tm.assert_numpy_array_equal(cat.__array__(), exp_cat) # however, copy is False by default # so this WILL change values cat = Categorical(["a", "b", "c", "a"]) s = Series(cat) assert s.values is cat s.cat.categories = [1, 2, 3] exp_s = np.array([1, 2, 3, 1], dtype=np.int64) tm.assert_numpy_array_equal(s.__array__(), exp_s) tm.assert_numpy_array_equal(cat.__array__(), exp_s) s[0] = 2 exp_s2 = np.array([2, 2, 3, 1], dtype=np.int64) tm.assert_numpy_array_equal(s.__array__(), exp_s2) tm.assert_numpy_array_equal(cat.__array__(), exp_s2)
Example #29
Source File: test_constructors.py From recruit with Apache License 2.0 | 5 votes |
def test_constructor(self, datetime_series, empty_series): assert datetime_series.index.is_all_dates # Pass in Series derived = Series(datetime_series) assert derived.index.is_all_dates assert tm.equalContents(derived.index, datetime_series.index) # Ensure new index is not created assert id(datetime_series.index) == id(derived.index) # Mixed type Series mixed = Series(['hello', np.NaN], index=[0, 1]) assert mixed.dtype == np.object_ assert mixed[1] is np.NaN assert not empty_series.index.is_all_dates assert not Series({}).index.is_all_dates # exception raised is of type Exception with pytest.raises(Exception, match="Data must be 1-dimensional"): Series(np.random.randn(3, 3), index=np.arange(3)) mixed.name = 'Series' rs = Series(mixed).name xp = 'Series' assert rs == xp # raise on MultiIndex GH4187 m = MultiIndex.from_arrays([[1, 2], [3, 4]]) msg = "initializing a Series from a MultiIndex is not supported" with pytest.raises(NotImplementedError, match=msg): Series(m)
Example #30
Source File: date_converters.py From recruit with Apache License 2.0 | 5 votes |
def _maybe_cast(arr): if not arr.dtype.type == np.object_: arr = np.array(arr, dtype=object) return arr