def test_period_array_readonly_object(): # https://github.com/pandas-dev/pandas/issues/25403 pa = period_array([pd.Period('2019-01-01')]) arr = np.asarray(pa, dtype='object') arr.setflags(write=False) result = period_array(arr) tm.assert_period_array_equal(result, pa) result = pd.Series(arr) tm.assert_series_equal(result, pd.Series(pa)) result = pd.DataFrame({"A": arr}) tm.assert_frame_equal(result, pd.DataFrame({"A": pa}))
def test_dti_with_period_data_raises(self): # GH#23675 data = pd.PeriodIndex(['2016Q1', '2016Q2'], freq='Q') with pytest.raises(TypeError, match="PeriodDtype data is invalid"): DatetimeIndex(data) with pytest.raises(TypeError, match="PeriodDtype data is invalid"): to_datetime(data) with pytest.raises(TypeError, match="PeriodDtype data is invalid"): DatetimeIndex(period_array(data)) with pytest.raises(TypeError, match="PeriodDtype data is invalid"): to_datetime(period_array(data))
def test_period_array_freq_mismatch(): arr = period_array(['2000', '2001'], freq='D') with pytest.raises(IncompatibleFrequency, match='freq'): PeriodArray(arr, freq='M') with pytest.raises(IncompatibleFrequency, match='freq'): PeriodArray(arr, freq=pd.tseries.offsets.MonthEnd())
def test_min_max_empty(self, skipna): arr = period_array([], freq='D') result = arr.min(skipna=skipna) assert result is pd.NaT result = arr.max(skipna=skipna) assert result is pd.NaT
def test_period_array_freq_mismatch(): arr = period_array(['2000', '2001'], freq='D') with tm.assert_raises_regex(IncompatibleFrequency, 'freq'): PeriodArray(arr, freq='M') with tm.assert_raises_regex(IncompatibleFrequency, 'freq'): PeriodArray(arr, freq=pd.tseries.offsets.MonthEnd())
def test_astype_copies(): arr = period_array(['2000', '2001', None], freq='D') result = arr.astype(np.int64, copy=False) assert result is arr._data result = arr.astype(np.int64, copy=True) assert result is not arr._data
def test_from_datetime64_freq_changes(): # https://github.com/pandas-dev/pandas/issues/23438 arr = pd.date_range("2017", periods=3, freq="D") result = PeriodArray._from_datetime64(arr, freq="M") expected = period_array(['2017-01-01', '2017-01-01', '2017-01-01'], freq="M") tm.assert_period_array_equal(result, expected)
def test_take_raises(): arr = period_array(['2000', '2001'], freq='D') with pytest.raises(IncompatibleFrequency, match='freq'): arr.take([0, -1], allow_fill=True, fill_value=pd.Period('2000', freq='W')) with pytest.raises(ValueError, match='foo'): arr.take([0, -1], allow_fill=True, fill_value='foo')
def test_take_raises(): arr = period_array(['2000', '2001'], freq='D') with tm.assert_raises_regex(IncompatibleFrequency, 'freq'): arr.take([0, -1], allow_fill=True, fill_value=pd.Period('2000', freq='W')) with tm.assert_raises_regex(ValueError, 'foo'): arr.take([0, -1], allow_fill=True, fill_value='foo')
def test_setitem_raises_incompatible_freq(): arr = PeriodArray(np.arange(3), freq="D") with pytest.raises(IncompatibleFrequency, match="freq"): arr[0] = pd.Period("2000", freq="A") other = period_array(['2000', '2001'], freq='A') with pytest.raises(IncompatibleFrequency, match="freq"): arr[[0, 1]] = other
def test_astype(dtype): # Need to ensure ordinals are astyped correctly for both # int32 and 64 arr = period_array(['2000', '2001', None], freq='D') result = arr.astype(dtype) # need pandas_dtype to handle int32 vs. int64 correctly expected = pandas_dtype(dtype) assert result.dtype == expected
def test_repr_small(): arr = period_array(['2000', '2001'], freq='D') result = str(arr) expected = ( "<PeriodArray>\n" "['2000-01-01', '2001-01-01']\n" "Length: 2, dtype: period[D]" ) assert result == expected
def test_constructor_infer_period(self): data = [pd.Period('2000', 'D'), pd.Period('2001', 'D'), None] result = pd.Series(data) expected = pd.Series(period_array(data)) tm.assert_series_equal(result, expected) assert result.dtype == 'Period[D]' data = np.asarray(data, dtype=object) tm.assert_series_equal(result, expected) assert result.dtype == 'Period[D]'
def test_astype_copies(): arr = period_array(['2000', '2001', None], freq='D') result = arr.astype(np.int64, copy=False) # Add the `.base`, since we now use `.asi8` which returns a view. # We could maybe override it in PeriodArray to return ._data directly. assert result.base is arr._data result = arr.astype(np.int64, copy=True) assert result is not arr._data tm.assert_numpy_array_equal(result, arr._data.view('i8'))
def test_astype(dtype): # We choose to ignore the sign and size of integers for # Period/Datetime/Timedelta astype arr = period_array(['2000', '2001', None], freq='D') result = arr.astype(dtype) if np.dtype(dtype).kind == 'u': expected_dtype = np.dtype('uint64') else: expected_dtype = np.dtype('int64') expected = arr.astype(expected_dtype) assert result.dtype == expected_dtype tm.assert_numpy_array_equal(result, expected)
def test_repr_large(): arr = period_array(['2000', '2001'] * 500, freq='D') result = str(arr) expected = ( "<PeriodArray>\n" "['2000-01-01', '2001-01-01', '2000-01-01', '2001-01-01', " "'2000-01-01',\n" " '2001-01-01', '2000-01-01', '2001-01-01', '2000-01-01', " "'2001-01-01',\n" " ...\n" " '2000-01-01', '2001-01-01', '2000-01-01', '2001-01-01', " "'2000-01-01',\n" " '2001-01-01', '2000-01-01', '2001-01-01', '2000-01-01', " "'2001-01-01']\n" "Length: 1000, dtype: period[D]" ) assert result == expected
def test_min_max(self): arr = period_array([ '2000-01-03', '2000-01-03', 'NaT', '2000-01-02', '2000-01-05', '2000-01-04', ], freq='D') result = arr.min() expected = pd.Period('2000-01-02', freq='D') assert result == expected result = arr.max() expected = pd.Period('2000-01-05', freq='D') assert result == expected result = arr.min(skipna=False) assert result is pd.NaT result = arr.max(skipna=False) assert result is pd.NaT
def test_fillna_raises(): arr = period_array(['2000', '2001', '2002'], freq='D') with pytest.raises(ValueError, match='Length'): arr.fillna(arr[:2])
def test_fillna_raises(): arr = period_array(['2000', '2001', '2002'], freq='D') with pytest.raises(ValueError, match='Length'): arr.fillna(arr[:2])
def array( data, # type: Sequence[object] dtype=None, # type: Optional[Union[str, np.dtype, ExtensionDtype]] copy=True, # type: bool ): # type: (...) -> ExtensionArray """ Create an array. .. versionadded:: 0.24.0 Parameters ---------- data : Sequence of objects The scalars inside `data` should be instances of the scalar type for `dtype`. It's expected that `data` represents a 1-dimensional array of data. When `data` is an Index or Series, the underlying array will be extracted from `data`. dtype : str, np.dtype, or ExtensionDtype, optional The dtype to use for the array. This may be a NumPy dtype or an extension type registered with pandas using :meth:`pandas.api.extensions.register_extension_dtype`. If not specified, there are two possibilities: 1. When `data` is a :class:`Series`, :class:`Index`, or :class:`ExtensionArray`, the `dtype` will be taken from the data. 2. Otherwise, pandas will attempt to infer the `dtype` from the data. Note that when `data` is a NumPy array, ``data.dtype`` is *not* used for inferring the array type. This is because NumPy cannot represent all the types of data that can be held in extension arrays. Currently, pandas will infer an extension dtype for sequences of ============================== ===================================== scalar type Array Type ============================= ===================================== * :class:`pandas.Interval` :class:`pandas.IntervalArray` * :class:`pandas.Period` :class:`pandas.arrays.PeriodArray` * :class:`datetime.datetime` :class:`pandas.arrays.DatetimeArray` * :class:`datetime.timedelta` :class:`pandas.arrays.TimedeltaArray` ============================= ===================================== For all other cases, NumPy's usual inference rules will be used. copy : bool, default True Whether to copy the data, even if not necessary. Depending on the type of `data`, creating the new array may require copying data, even if ``copy=False``. Returns ------- ExtensionArray The newly created array. Raises ------ ValueError When `data` is not 1-dimensional. See Also -------- numpy.array : Construct a NumPy array. arrays.PandasArray : ExtensionArray wrapping a NumPy array. Series : Construct a pandas Series. Index : Construct a pandas Index. Notes ----- Omitting the `dtype` argument means pandas will attempt to infer the best array type from the values in the data. As new array types are added by pandas and 3rd party libraries, the "best" array type may change. We recommend specifying `dtype` to ensure that 1. the correct array type for the data is returned 2. the returned array type doesn't change as new extension types are added by pandas and third-party libraries Additionally, if the underlying memory representation of the returned array matters, we recommend specifying the `dtype` as a concrete object rather than a string alias or allowing it to be inferred. For example, a future version of pandas or a 3rd-party library may include a dedicated ExtensionArray for string data. In this event, the following would no longer return a :class:`arrays.PandasArray` backed by a NumPy array. >>> pd.array(['a', 'b'], dtype=str) <PandasArray> ['a', 'b'] Length: 2, dtype: str32 This would instead return the new ExtensionArray dedicated for string data. If you really need the new array to be backed by a NumPy array, specify that in the dtype. >>> pd.array(['a', 'b'], dtype=np.dtype("<U1")) <PandasArray> ['a', 'b'] Length: 2, dtype: str32 Or use the dedicated constructor for the array you're expecting, and wrap that in a PandasArray >>> pd.array(np.array(['a', 'b'], dtype='<U1')) <PandasArray> ['a', 'b'] Length: 2, dtype: str32 Examples -------- If a dtype is not specified, `data` is passed through to :meth:`numpy.array`, and a :class:`arrays.PandasArray` is returned. >>> pd.array([1, 2]) <PandasArray> [1, 2] Length: 2, dtype: int64 Or the NumPy dtype can be specified >>> pd.array([1, 2], dtype=np.dtype("int32")) <PandasArray> [1, 2] Length: 2, dtype: int32 You can use the string alias for `dtype` >>> pd.array(['a', 'b', 'a'], dtype='category') [a, b, a] Categories (2, object): [a, b] Or specify the actual dtype >>> pd.array(['a', 'b', 'a'], ... dtype=pd.CategoricalDtype(['a', 'b', 'c'], ordered=True)) [a, b, a] Categories (3, object): [a < b < c] Because omitting the `dtype` passes the data through to NumPy, a mixture of valid integers and NA will return a floating-point NumPy array. >>> pd.array([1, 2, np.nan]) <PandasArray> [1.0, 2.0, nan] Length: 3, dtype: float64 To use pandas' nullable :class:`pandas.arrays.IntegerArray`, specify the dtype: >>> pd.array([1, 2, np.nan], dtype='Int64') <IntegerArray> [1, 2, NaN] Length: 3, dtype: Int64 Pandas will infer an ExtensionArray for some types of data: >>> pd.array([pd.Period('2000', freq="D"), pd.Period("2000", freq="D")]) <PeriodArray> ['2000-01-01', '2000-01-01'] Length: 2, dtype: period[D] `data` must be 1-dimensional. A ValueError is raised when the input has the wrong dimensionality. >>> pd.array(1) Traceback (most recent call last): ... ValueError: Cannot pass scalar '1' to 'pandas.array'. """ from pandas.core.arrays import ( period_array, ExtensionArray, IntervalArray, PandasArray, DatetimeArray, TimedeltaArray, ) from pandas.core.internals.arrays import extract_array if lib.is_scalar(data): msg = ("Cannot pass scalar '{}' to 'pandas.array'.") raise ValueError(msg.format(data)) data = extract_array(data, extract_numpy=True) if dtype is None and isinstance(data, ExtensionArray): dtype = data.dtype # this returns None for not-found dtypes. if isinstance(dtype, compat.string_types): dtype = registry.find(dtype) or dtype if is_extension_array_dtype(dtype): cls = dtype.construct_array_type() return cls._from_sequence(data, dtype=dtype, copy=copy) if dtype is None: inferred_dtype = lib.infer_dtype(data) if inferred_dtype == 'period': try: return period_array(data, copy=copy) except tslibs.IncompatibleFrequency: # We may have a mixture of frequencies. # We choose to return an ndarray, rather than raising. pass elif inferred_dtype == 'interval': try: return IntervalArray(data, copy=copy) except ValueError: # We may have a mixture of `closed` here. # We choose to return an ndarray, rather than raising. pass elif inferred_dtype.startswith('datetime'): # datetime, datetime64 try: return DatetimeArray._from_sequence(data, copy=copy) except ValueError: # Mixture of timezones, fall back to PandasArray pass elif inferred_dtype.startswith('timedelta'): # timedelta, timedelta64 return TimedeltaArray._from_sequence(data, copy=copy) # TODO(BooleanArray): handle this type result = PandasArray._from_sequence(data, dtype=dtype, copy=copy) return result
def test_astype_period(): arr = period_array(['2000', '2001', None], freq='D') result = arr.astype(PeriodDtype("M")) expected = period_array(['2000', '2001', None], freq='M') tm.assert_period_array_equal(result, expected)
def test_astype_datetime(other): arr = period_array(["2000", "2001", None], freq="D") # slice off the [ns] so that the regex matches. with pytest.raises(TypeError, match=other[:-4]): arr.astype(other)
@pytest.mark.parametrize("data, dtype, expected", [ # Basic NumPy defaults. ([1, 2], None, PandasArray(np.array([1, 2]))), ([1, 2], object, PandasArray(np.array([1, 2], dtype=object))), ([1, 2], np.dtype('float32'), PandasArray(np.array([1., 2.0], dtype=np.dtype('float32')))), (np.array([1, 2]), None, PandasArray(np.array([1, 2]))), # String alias passes through to NumPy ([1, 2], 'float32', PandasArray(np.array([1, 2], dtype='float32'))), # Period alias ([pd.Period('2000', 'D'), pd.Period('2001', 'D')], 'Period[D]', period_array(['2000', '2001'], freq='D')), # Period dtype ([pd.Period('2000', 'D')], pd.PeriodDtype('D'), period_array(['2000'], freq='D')), # Datetime (naive) ([1, 2], np.dtype('datetime64[ns]'), pd.arrays.DatetimeArray._from_sequence( np.array([1, 2], dtype='datetime64[ns]'))), (np.array([1, 2], dtype='datetime64[ns]'), None, pd.arrays.DatetimeArray._from_sequence( np.array([1, 2], dtype='datetime64[ns]'))), (pd.DatetimeIndex(['2000', '2001']), np.dtype('datetime64[ns]'),
def sanitize_array( data, index, dtype=None, copy: bool = False, raise_cast_failure: bool = False ): """ Sanitize input data to an ndarray, copy if specified, coerce to the dtype if specified. """ if dtype is not None: dtype = pandas_dtype(dtype) if isinstance(data, ma.MaskedArray): mask = ma.getmaskarray(data) if mask.any(): data, fill_value = maybe_upcast(data, copy=True) data.soften_mask() # set hardmask False if it was True data[mask] = fill_value else: data = data.copy() # extract ndarray or ExtensionArray, ensure we have no PandasArray data = extract_array(data, extract_numpy=True) # GH#846 if isinstance(data, np.ndarray): if dtype is not None and is_float_dtype(data.dtype) and is_integer_dtype(dtype): # possibility of nan -> garbage try: subarr = _try_cast(data, dtype, copy, True) except ValueError: if copy: subarr = data.copy() else: subarr = np.array(data, copy=False) else: # we will try to copy be-definition here subarr = _try_cast(data, dtype, copy, raise_cast_failure) elif isinstance(data, ABCExtensionArray): # it is already ensured above this is not a PandasArray subarr = data if dtype is not None: subarr = subarr.astype(dtype, copy=copy) elif copy: subarr = subarr.copy() return subarr elif isinstance(data, (list, tuple)) and len(data) > 0: if dtype is not None: subarr = _try_cast(data, dtype, copy, raise_cast_failure) else: subarr = maybe_convert_platform(data) subarr = maybe_cast_to_datetime(subarr, dtype) elif isinstance(data, range): # GH#16804 arr = np.arange(data.start, data.stop, data.step, dtype="int64") subarr = _try_cast(arr, dtype, copy, raise_cast_failure) else: subarr = _try_cast(data, dtype, copy, raise_cast_failure) # scalar like, GH if getattr(subarr, "ndim", 0) == 0: if isinstance(data, list): # pragma: no cover subarr = np.array(data, dtype=object) elif index is not None: value = data # figure out the dtype from the value (upcast if necessary) if dtype is None: dtype, value = infer_dtype_from_scalar(value) else: # need to possibly convert the value here value = maybe_cast_to_datetime(value, dtype) subarr = construct_1d_arraylike_from_scalar(value, len(index), dtype) else: return subarr.item() # the result that we want elif subarr.ndim == 1: if index is not None: # a 1-element ndarray if len(subarr) != len(index) and len(subarr) == 1: subarr = construct_1d_arraylike_from_scalar( subarr[0], len(index), subarr.dtype ) elif subarr.ndim > 1: if isinstance(data, np.ndarray): raise Exception("Data must be 1-dimensional") else: subarr = com.asarray_tuplesafe(data, dtype=dtype) if not (is_extension_array_dtype(subarr.dtype) or is_extension_array_dtype(dtype)): # This is to prevent mixed-type Series getting all casted to # NumPy string type, e.g. NaN --> '-1#IND'. if issubclass(subarr.dtype.type, str): # GH#16605 # If not empty convert the data to dtype # GH#19853: If data is a scalar, subarr has already the result if not lib.is_scalar(data): if not np.all(isna(data)): data = np.array(data, dtype=dtype, copy=False) subarr = np.array(data, dtype=object, copy=copy) if is_object_dtype(subarr.dtype) and not is_object_dtype(dtype): inferred = lib.infer_dtype(subarr, skipna=False) if inferred == "period": from pandas.core.arrays import period_array try: subarr = period_array(subarr) except IncompatibleFrequency: pass return subarr
def test_where_different_freq_raises(other): ser = pd.Series(period_array(["2000", "2001", "2002"], freq="D")) cond = np.array([True, False, True]) with pytest.raises(IncompatibleFrequency, match="freq"): ser.where(cond, other)
def test_astype_categorical(): arr = period_array(['2000', '2001', '2001', None], freq='D') result = arr.astype('category') categories = pd.PeriodIndex(['2000', '2001'], freq='D') expected = pd.Categorical.from_codes([0, 1, 1, -1], categories=categories) tm.assert_categorical_equal(result, expected)
def test_astype_period(): arr = period_array(['2000', '2001', None], freq='D') result = arr.astype(PeriodDtype("M")) expected = period_array(['2000', '2001', None], freq='M') tm.assert_period_array_equal(result, expected)
np.array([1, 2], dtype=np.float16), None, PandasArray(np.array([1, 2], dtype=np.float16)), ), # idempotency with e.g. pd.array(pd.array([1, 2], dtype="int64")) ( PandasArray(np.array([1, 2], dtype=np.int32)), None, PandasArray(np.array([1, 2], dtype=np.int32)), ), # Period alias ( [pd.Period("2000", "D"), pd.Period("2001", "D")], "Period[D]", period_array(["2000", "2001"], freq="D"), ), # Period dtype ( [pd.Period("2000", "D")], pd.PeriodDtype("D"), period_array(["2000"], freq="D"), ), # Datetime (naive) ( [1, 2], np.dtype("datetime64[ns]"), DatetimeArray._from_sequence( np.array([1, 2], dtype="datetime64[ns]")), ), (
def test_period_array_raises(data, freq, msg): with pytest.raises(IncompatibleFrequency, match=msg): period_array(data, freq)
def test_from_datetime64_freq_changes(): # https://github.com/pandas-dev/pandas/issues/23438 arr = pd.date_range("2017", periods=3, freq="D") result = PeriodArray._from_datetime64(arr, freq="M") expected = period_array(["2017-01-01", "2017-01-01", "2017-01-01"], freq="M") tm.assert_period_array_equal(result, expected)
def test_fillna_copies(): arr = period_array(["2000", "2001", "2002"], freq="D") result = arr.fillna(pd.Period("2000", "D")) assert result is not arr
"data, dtype, expected", [ # Basic NumPy defaults. ([1, 2], None, PandasArray(np.array([1, 2]))), ([1, 2], object, PandasArray(np.array([1, 2], dtype=object))), ([1, 2], np.dtype('float32'), PandasArray(np.array([1., 2.0], dtype=np.dtype('float32')))), (np.array([1, 2]), None, PandasArray(np.array([1, 2]))), # String alias passes through to NumPy ([1, 2], 'float32', PandasArray(np.array([1, 2], dtype='float32'))), # Period alias ([pd.Period('2000', 'D'), pd.Period('2001', 'D') ], 'Period[D]', period_array(['2000', '2001'], freq='D')), # Period dtype ([pd.Period('2000', 'D') ], pd.PeriodDtype('D'), period_array(['2000'], freq='D')), # Datetime (naive) ([1, 2], np.dtype('datetime64[ns]'), pd.arrays.DatetimeArray._from_sequence( np.array([1, 2], dtype='datetime64[ns]'))), (np.array([1, 2], dtype='datetime64[ns]'), None, pd.arrays.DatetimeArray._from_sequence( np.array([1, 2], dtype='datetime64[ns]'))), (pd.DatetimeIndex(['2000', '2001']), np.dtype('datetime64[ns]'), pd.arrays.DatetimeArray._from_sequence(['2000', '2001'])), (pd.DatetimeIndex(['2000', '2001']), None,
def test_astype_datetime(other): arr = period_array(['2000', '2001', None], freq='D') # slice off the [ns] so that the regex matches. with tm.assert_raises_regex(TypeError, other[:-4]): arr.astype(other)
def test_sub_period(): arr = period_array(["2000", "2001"], freq="D") other = pd.Period("2000", freq="M") with pytest.raises(IncompatibleFrequency, match="freq"): arr - other
def test_sub_period(): arr = period_array(["2000", "2001"], freq="D") other = pd.Period("2000", freq="M") with pytest.raises(IncompatibleFrequency, match="freq"): arr - other # ---------------------------------------------------------------------------- # Methods @pytest.mark.parametrize( "other", [ pd.Period("2000", freq="H"), period_array(["2000", "2001", "2000"], freq="H") ], ) def test_where_different_freq_raises(other): ser = pd.Series(period_array(["2000", "2001", "2002"], freq="D")) cond = np.array([True, False, True]) with pytest.raises(IncompatibleFrequency, match="freq"): ser.where(cond, other) # ---------------------------------------------------------------------------- # Printing def test_repr_small(): arr = period_array(["2000", "2001"], freq="D")
def test_fillna_raises(): arr = period_array(['2000', '2001', '2002'], freq='D') with tm.assert_raises_regex(ValueError, 'Length'): arr.fillna(arr[:2])
def sanitize_array(data, index, dtype=None, copy=False, raise_cast_failure=False): """ Sanitize input data to an ndarray, copy if specified, coerce to the dtype if specified. """ if dtype is not None: dtype = pandas_dtype(dtype) if isinstance(data, ma.MaskedArray): mask = ma.getmaskarray(data) if mask.any(): data, fill_value = maybe_upcast(data, copy=True) data.soften_mask() # set hardmask False if it was True data[mask] = fill_value else: data = data.copy() data = extract_array(data, extract_numpy=True) # GH#846 if isinstance(data, np.ndarray): if dtype is not None: subarr = np.array(data, copy=False) # possibility of nan -> garbage if is_float_dtype(data.dtype) and is_integer_dtype(dtype): try: subarr = _try_cast(data, True, dtype, copy, True) except ValueError: if copy: subarr = data.copy() else: subarr = _try_cast(data, True, dtype, copy, raise_cast_failure) elif isinstance(data, Index): # don't coerce Index types # e.g. indexes can have different conversions (so don't fast path # them) # GH#6140 subarr = sanitize_index(data, index, copy=copy) else: # we will try to copy be-definition here subarr = _try_cast(data, True, dtype, copy, raise_cast_failure) elif isinstance(data, ExtensionArray): if isinstance(data, ABCPandasArray): # We don't want to let people put our PandasArray wrapper # (the output of Series/Index.array), into a Series. So # we explicitly unwrap it here. subarr = data.to_numpy() else: subarr = data # everything else in this block must also handle ndarray's, # becuase we've unwrapped PandasArray into an ndarray. if dtype is not None: subarr = data.astype(dtype) if copy: subarr = data.copy() return subarr elif isinstance(data, (list, tuple)) and len(data) > 0: if dtype is not None: try: subarr = _try_cast(data, False, dtype, copy, raise_cast_failure) except Exception: if raise_cast_failure: # pragma: no cover raise subarr = np.array(data, dtype=object, copy=copy) subarr = lib.maybe_convert_objects(subarr) else: subarr = maybe_convert_platform(data) subarr = maybe_cast_to_datetime(subarr, dtype) elif isinstance(data, range): # GH#16804 start, stop, step = get_range_parameters(data) arr = np.arange(start, stop, step, dtype='int64') subarr = _try_cast(arr, False, dtype, copy, raise_cast_failure) else: subarr = _try_cast(data, False, dtype, copy, raise_cast_failure) # scalar like, GH if getattr(subarr, 'ndim', 0) == 0: if isinstance(data, list): # pragma: no cover subarr = np.array(data, dtype=object) elif index is not None: value = data # figure out the dtype from the value (upcast if necessary) if dtype is None: dtype, value = infer_dtype_from_scalar(value) else: # need to possibly convert the value here value = maybe_cast_to_datetime(value, dtype) subarr = construct_1d_arraylike_from_scalar( value, len(index), dtype) else: return subarr.item() # the result that we want elif subarr.ndim == 1: if index is not None: # a 1-element ndarray if len(subarr) != len(index) and len(subarr) == 1: subarr = construct_1d_arraylike_from_scalar( subarr[0], len(index), subarr.dtype) elif subarr.ndim > 1: if isinstance(data, np.ndarray): raise Exception('Data must be 1-dimensional') else: subarr = com.asarray_tuplesafe(data, dtype=dtype) # This is to prevent mixed-type Series getting all casted to # NumPy string type, e.g. NaN --> '-1#IND'. if issubclass(subarr.dtype.type, compat.string_types): # GH#16605 # If not empty convert the data to dtype # GH#19853: If data is a scalar, subarr has already the result if not lib.is_scalar(data): if not np.all(isna(data)): data = np.array(data, dtype=dtype, copy=False) subarr = np.array(data, dtype=object, copy=copy) if is_object_dtype(subarr.dtype) and dtype != 'object': inferred = lib.infer_dtype(subarr, skipna=False) if inferred == 'period': try: subarr = period_array(subarr) except IncompatibleFrequency: pass return subarr
def test_asi8(): result = period_array(["2000", "2001", None], freq="D").asi8 expected = np.array([10957, 11323, iNaT]) tm.assert_numpy_array_equal(result, expected)
def sanitize_array(data, index, dtype=None, copy=False, raise_cast_failure=False): """ Sanitize input data to an ndarray, copy if specified, coerce to the dtype if specified. """ if dtype is not None: dtype = pandas_dtype(dtype) if isinstance(data, ma.MaskedArray): mask = ma.getmaskarray(data) if mask.any(): data, fill_value = maybe_upcast(data, copy=True) data.soften_mask() # set hardmask False if it was True data[mask] = fill_value else: data = data.copy() data = extract_array(data, extract_numpy=True) # GH#846 if isinstance(data, np.ndarray): if dtype is not None: subarr = np.array(data, copy=False) # possibility of nan -> garbage if is_float_dtype(data.dtype) and is_integer_dtype(dtype): try: subarr = _try_cast(data, True, dtype, copy, True) except ValueError: if copy: subarr = data.copy() else: subarr = _try_cast(data, True, dtype, copy, raise_cast_failure) elif isinstance(data, Index): # don't coerce Index types # e.g. indexes can have different conversions (so don't fast path # them) # GH#6140 subarr = sanitize_index(data, index, copy=copy) else: # we will try to copy be-definition here subarr = _try_cast(data, True, dtype, copy, raise_cast_failure) elif isinstance(data, ExtensionArray): if isinstance(data, ABCPandasArray): # We don't want to let people put our PandasArray wrapper # (the output of Series/Index.array), into a Series. So # we explicitly unwrap it here. subarr = data.to_numpy() else: subarr = data # everything else in this block must also handle ndarray's, # becuase we've unwrapped PandasArray into an ndarray. if dtype is not None: subarr = data.astype(dtype) if copy: subarr = data.copy() return subarr elif isinstance(data, (list, tuple)) and len(data) > 0: if dtype is not None: try: subarr = _try_cast(data, False, dtype, copy, raise_cast_failure) except Exception: if raise_cast_failure: # pragma: no cover raise subarr = np.array(data, dtype=object, copy=copy) subarr = lib.maybe_convert_objects(subarr) else: subarr = maybe_convert_platform(data) subarr = maybe_cast_to_datetime(subarr, dtype) elif isinstance(data, range): # GH#16804 arr = np.arange(data.start, data.stop, data.step, dtype='int64') subarr = _try_cast(arr, False, dtype, copy, raise_cast_failure) else: subarr = _try_cast(data, False, dtype, copy, raise_cast_failure) # scalar like, GH if getattr(subarr, 'ndim', 0) == 0: if isinstance(data, list): # pragma: no cover subarr = np.array(data, dtype=object) elif index is not None: value = data # figure out the dtype from the value (upcast if necessary) if dtype is None: dtype, value = infer_dtype_from_scalar(value) else: # need to possibly convert the value here value = maybe_cast_to_datetime(value, dtype) subarr = construct_1d_arraylike_from_scalar( value, len(index), dtype) else: return subarr.item() # the result that we want elif subarr.ndim == 1: if index is not None: # a 1-element ndarray if len(subarr) != len(index) and len(subarr) == 1: subarr = construct_1d_arraylike_from_scalar( subarr[0], len(index), subarr.dtype) elif subarr.ndim > 1: if isinstance(data, np.ndarray): raise Exception('Data must be 1-dimensional') else: subarr = com.asarray_tuplesafe(data, dtype=dtype) # This is to prevent mixed-type Series getting all casted to # NumPy string type, e.g. NaN --> '-1#IND'. if issubclass(subarr.dtype.type, str): # GH#16605 # If not empty convert the data to dtype # GH#19853: If data is a scalar, subarr has already the result if not lib.is_scalar(data): if not np.all(isna(data)): data = np.array(data, dtype=dtype, copy=False) subarr = np.array(data, dtype=object, copy=copy) if is_object_dtype(subarr.dtype) and dtype != 'object': inferred = lib.infer_dtype(subarr, skipna=False) if inferred == 'period': try: subarr = period_array(subarr) except IncompatibleFrequency: pass return subarr
def test_sub_period(): arr = period_array(["2000", "2001"], freq="D") other = pd.Period("2000", freq="M") with pytest.raises(IncompatibleFrequency, match="freq"): arr - other # ---------------------------------------------------------------------------- # Methods @pytest.mark.parametrize( "other", [pd.Period("2000", freq="H"), period_array(["2000", "2001", "2000"], freq="H")], ) def test_where_different_freq_raises(other): ser = pd.Series(period_array(["2000", "2001", "2002"], freq="D")) cond = np.array([True, False, True]) with pytest.raises(IncompatibleFrequency, match="freq"): ser.where(cond, other) # ---------------------------------------------------------------------------- # Printing def test_repr_small(): arr = period_array(["2000", "2001"], freq="D") result = str(arr)
# ---------------------------------------------------------------------------- # Ops def test_sub_period(): arr = period_array(['2000', '2001'], freq='D') other = pd.Period("2000", freq="M") with pytest.raises(IncompatibleFrequency, match="freq"): arr - other # ---------------------------------------------------------------------------- # Methods @pytest.mark.parametrize('other', [ pd.Period('2000', freq='H'), period_array(['2000', '2001', '2000'], freq='H') ]) def test_where_different_freq_raises(other): ser = pd.Series(period_array(['2000', '2001', '2002'], freq='D')) cond = np.array([True, False, True]) with pytest.raises(IncompatibleFrequency, match="Input has different freq=H"): ser.where(cond, other) # ---------------------------------------------------------------------------- # Printing def test_repr_small(): arr = period_array(['2000', '2001'], freq='D') result = str(arr)
def array( data: Sequence[object], dtype: Optional[Union[str, np.dtype, ExtensionDtype]] = None, copy: bool = True, ) -> ABCExtensionArray: """ Create an array. .. versionadded:: 0.24.0 Parameters ---------- data : Sequence of objects The scalars inside `data` should be instances of the scalar type for `dtype`. It's expected that `data` represents a 1-dimensional array of data. When `data` is an Index or Series, the underlying array will be extracted from `data`. dtype : str, np.dtype, or ExtensionDtype, optional The dtype to use for the array. This may be a NumPy dtype or an extension type registered with pandas using :meth:`pandas.api.extensions.register_extension_dtype`. If not specified, there are two possibilities: 1. When `data` is a :class:`Series`, :class:`Index`, or :class:`ExtensionArray`, the `dtype` will be taken from the data. 2. Otherwise, pandas will attempt to infer the `dtype` from the data. Note that when `data` is a NumPy array, ``data.dtype`` is *not* used for inferring the array type. This is because NumPy cannot represent all the types of data that can be held in extension arrays. Currently, pandas will infer an extension dtype for sequences of ============================== ===================================== Scalar Type Array Type ============================== ===================================== :class:`pandas.Interval` :class:`pandas.arrays.IntervalArray` :class:`pandas.Period` :class:`pandas.arrays.PeriodArray` :class:`datetime.datetime` :class:`pandas.arrays.DatetimeArray` :class:`datetime.timedelta` :class:`pandas.arrays.TimedeltaArray` :class:`int` :class:`pandas.arrays.IntegerArray` :class:`str` :class:`pandas.arrays.StringArray` :class:`bool` :class:`pandas.arrays.BooleanArray` ============================== ===================================== For all other cases, NumPy's usual inference rules will be used. .. versionchanged:: 1.0.0 Pandas infers nullable-integer dtype for integer data, string dtype for string data, and nullable-boolean dtype for boolean data. copy : bool, default True Whether to copy the data, even if not necessary. Depending on the type of `data`, creating the new array may require copying data, even if ``copy=False``. Returns ------- ExtensionArray The newly created array. Raises ------ ValueError When `data` is not 1-dimensional. See Also -------- numpy.array : Construct a NumPy array. Series : Construct a pandas Series. Index : Construct a pandas Index. arrays.PandasArray : ExtensionArray wrapping a NumPy array. Series.array : Extract the array stored within a Series. Notes ----- Omitting the `dtype` argument means pandas will attempt to infer the best array type from the values in the data. As new array types are added by pandas and 3rd party libraries, the "best" array type may change. We recommend specifying `dtype` to ensure that 1. the correct array type for the data is returned 2. the returned array type doesn't change as new extension types are added by pandas and third-party libraries Additionally, if the underlying memory representation of the returned array matters, we recommend specifying the `dtype` as a concrete object rather than a string alias or allowing it to be inferred. For example, a future version of pandas or a 3rd-party library may include a dedicated ExtensionArray for string data. In this event, the following would no longer return a :class:`arrays.PandasArray` backed by a NumPy array. >>> pd.array(['a', 'b'], dtype=str) <PandasArray> ['a', 'b'] Length: 2, dtype: str32 This would instead return the new ExtensionArray dedicated for string data. If you really need the new array to be backed by a NumPy array, specify that in the dtype. >>> pd.array(['a', 'b'], dtype=np.dtype("<U1")) <PandasArray> ['a', 'b'] Length: 2, dtype: str32 Finally, Pandas has arrays that mostly overlap with NumPy * :class:`arrays.DatetimeArray` * :class:`arrays.TimedeltaArray` When data with a ``datetime64[ns]`` or ``timedelta64[ns]`` dtype is passed, pandas will always return a ``DatetimeArray`` or ``TimedeltaArray`` rather than a ``PandasArray``. This is for symmetry with the case of timezone-aware data, which NumPy does not natively support. >>> pd.array(['2015', '2016'], dtype='datetime64[ns]') <DatetimeArray> ['2015-01-01 00:00:00', '2016-01-01 00:00:00'] Length: 2, dtype: datetime64[ns] >>> pd.array(["1H", "2H"], dtype='timedelta64[ns]') <TimedeltaArray> ['01:00:00', '02:00:00'] Length: 2, dtype: timedelta64[ns] Examples -------- If a dtype is not specified, pandas will infer the best dtype from the values. See the description of `dtype` for the types pandas infers for. >>> pd.array([1, 2]) <IntegerArray> [1, 2] Length: 2, dtype: Int64 >>> pd.array([1, 2, np.nan]) <IntegerArray> [1, 2, NaN] Length: 3, dtype: Int64 >>> pd.array(["a", None, "c"]) <StringArray> ['a', nan, 'c'] Length: 3, dtype: string >>> pd.array([pd.Period('2000', freq="D"), pd.Period("2000", freq="D")]) <PeriodArray> ['2000-01-01', '2000-01-01'] Length: 2, dtype: period[D] You can use the string alias for `dtype` >>> pd.array(['a', 'b', 'a'], dtype='category') [a, b, a] Categories (2, object): [a, b] Or specify the actual dtype >>> pd.array(['a', 'b', 'a'], ... dtype=pd.CategoricalDtype(['a', 'b', 'c'], ordered=True)) [a, b, a] Categories (3, object): [a < b < c] If pandas does not infer a dedicated extension type a :class:`arrays.PandasArray` is returned. >>> pd.array([1.1, 2.2]) <PandasArray> [1.1, 2.2] Length: 2, dtype: float64 As mentioned in the "Notes" section, new extension types may be added in the future (by pandas or 3rd party libraries), causing the return value to no longer be a :class:`arrays.PandasArray`. Specify the `dtype` as a NumPy dtype if you need to ensure there's no future change in behavior. >>> pd.array([1, 2], dtype=np.dtype("int32")) <PandasArray> [1, 2] Length: 2, dtype: int32 `data` must be 1-dimensional. A ValueError is raised when the input has the wrong dimensionality. >>> pd.array(1) Traceback (most recent call last): ... ValueError: Cannot pass scalar '1' to 'pandas.array'. """ from pandas.core.arrays import ( period_array, BooleanArray, IntegerArray, IntervalArray, PandasArray, DatetimeArray, TimedeltaArray, StringArray, ) if lib.is_scalar(data): msg = f"Cannot pass scalar '{data}' to 'pandas.array'." raise ValueError(msg) if dtype is None and isinstance( data, (ABCSeries, ABCIndexClass, ABCExtensionArray) ): dtype = data.dtype data = extract_array(data, extract_numpy=True) # this returns None for not-found dtypes. if isinstance(dtype, str): dtype = registry.find(dtype) or dtype if is_extension_array_dtype(dtype): cls = cast(ExtensionDtype, dtype).construct_array_type() return cls._from_sequence(data, dtype=dtype, copy=copy) if dtype is None: inferred_dtype = lib.infer_dtype(data, skipna=True) if inferred_dtype == "period": try: return period_array(data, copy=copy) except IncompatibleFrequency: # We may have a mixture of frequencies. # We choose to return an ndarray, rather than raising. pass elif inferred_dtype == "interval": try: return IntervalArray(data, copy=copy) except ValueError: # We may have a mixture of `closed` here. # We choose to return an ndarray, rather than raising. pass elif inferred_dtype.startswith("datetime"): # datetime, datetime64 try: return DatetimeArray._from_sequence(data, copy=copy) except ValueError: # Mixture of timezones, fall back to PandasArray pass elif inferred_dtype.startswith("timedelta"): # timedelta, timedelta64 return TimedeltaArray._from_sequence(data, copy=copy) elif inferred_dtype == "string": return StringArray._from_sequence(data, copy=copy) elif inferred_dtype == "integer": return IntegerArray._from_sequence(data, copy=copy) elif inferred_dtype == "boolean": return BooleanArray._from_sequence(data, copy=copy) # Pandas overrides NumPy for # 1. datetime64[ns] # 2. timedelta64[ns] # so that a DatetimeArray is returned. if is_datetime64_ns_dtype(dtype): return DatetimeArray._from_sequence(data, dtype=dtype, copy=copy) elif is_timedelta64_ns_dtype(dtype): return TimedeltaArray._from_sequence(data, dtype=dtype, copy=copy) result = PandasArray._from_sequence(data, dtype=dtype, copy=copy) return result
def test_astype_categorical(): arr = period_array(['2000', '2001', '2001', None], freq='D') result = arr.astype('category') categories = pd.PeriodIndex(['2000', '2001'], freq='D') expected = pd.Categorical.from_codes([0, 1, 1, -1], categories=categories) tm.assert_categorical_equal(result, expected)
def test_sub_period(): arr = period_array(['2000', '2001'], freq='D') other = pd.Period("2000", freq="M") with pytest.raises(IncompatibleFrequency, match="freq"): arr - other # ---------------------------------------------------------------------------- # Methods @pytest.mark.parametrize('other', [ pd.Period('2000', freq='H'), period_array(['2000', '2001', '2000'], freq='H') ]) def test_where_different_freq_raises(other): ser = pd.Series(period_array(['2000', '2001', '2002'], freq='D')) cond = np.array([True, False, True]) with pytest.raises(IncompatibleFrequency, match="freq"): ser.where(cond, other) # ---------------------------------------------------------------------------- # Printing def test_repr_small(): arr = period_array(['2000', '2001'], freq='D') result = str(arr)
def test_astype_datetime(other): arr = period_array(['2000', '2001', None], freq='D') # slice off the [ns] so that the regex matches. with pytest.raises(TypeError, match=other[:-4]): arr.astype(other)
def test_where_different_freq_raises(other): ser = pd.Series(period_array(['2000', '2001', '2002'], freq='D')) cond = np.array([True, False, True]) with pytest.raises(IncompatibleFrequency, match="Input has different freq=H"): ser.where(cond, other)
def test_fillna_copies(): arr = period_array(['2000', '2001', '2002'], freq='D') result = arr.fillna(pd.Period("2000", "D")) assert result is not arr
def test_astype_period(): arr = period_array(["2000", "2001", None], freq="D") result = arr.astype(PeriodDtype("M")) expected = period_array(["2000", "2001", None], freq="M") tm.assert_period_array_equal(result, expected)
def test_sub_period(): arr = period_array(['2000', '2001'], freq='D') other = pd.Period("2000", freq="M") with pytest.raises(IncompatibleFrequency, match="freq"): arr - other
def test_fillna_raises(): arr = period_array(["2000", "2001", "2002"], freq="D") with pytest.raises(ValueError, match="Length"): arr.fillna(arr[:2])
def test_fillna_copies(): arr = period_array(['2000', '2001', '2002'], freq='D') result = arr.fillna(pd.Period("2000", "D")) assert result is not arr
def test_astype_categorical(): arr = period_array(["2000", "2001", "2001", None], freq="D") result = arr.astype("category") categories = pd.PeriodIndex(["2000", "2001"], freq="D") expected = pd.Categorical.from_codes([0, 1, 1, -1], categories=categories) tm.assert_categorical_equal(result, expected)
def test_period_array_ok(data, freq, expected): result = period_array(data, freq=freq).asi8 expected = np.asarray(expected, dtype=np.int64) tm.assert_numpy_array_equal(result, expected)
def tet_sub_period(): arr = period_array(['2000', '2001'], freq='D') other = pd.Period("2000", freq="M") with tm.assert_raises_regex(IncompatibleFrequency, "freq"): arr - other
def test_period_array_raises(data, freq, msg): with pytest.raises(IncompatibleFrequency, match=msg): period_array(data, freq)
def test_period_array_ok(data, freq, expected): result = period_array(data, freq=freq).asi8 expected = np.asarray(expected, dtype=np.int64) tm.assert_numpy_array_equal(result, expected)
def test_asi8(): result = period_array(['2000', '2001', None], freq='D').asi8 expected = np.array([10957, 11323, iNaT]) tm.assert_numpy_array_equal(result, expected)
def test_period_array_raises(data, freq, msg): with tm.assert_raises_regex(IncompatibleFrequency, msg): period_array(data, freq)
def test_asi8(): result = period_array(['2000', '2001', None], freq='D').asi8 expected = np.array([10957, 11323, iNaT]) tm.assert_numpy_array_equal(result, expected)
def test_where_different_freq_raises(other): ser = pd.Series(period_array(['2000', '2001', '2002'], freq='D')) cond = np.array([True, False, True]) with pytest.raises(IncompatibleFrequency, match="Input has different freq=H"): ser.where(cond, other)