def test_set_na(self, left_right_dtypes): left, right = left_right_dtypes result = IntervalArray.from_arrays(left, right) result[0] = np.nan expected_left = Index([left._na_value] + list(left[1:])) expected_right = Index([right._na_value] + list(right[1:])) expected = IntervalArray.from_arrays(expected_left, expected_right) tm.assert_extension_array_equal(result, expected)
def test_arrow_array_missing(): import pyarrow as pa from pandas.core.arrays._arrow_utils import ArrowIntervalType arr = IntervalArray.from_breaks([0.0, 1.0, 2.0, 3.0]) arr[1] = None result = pa.array(arr) assert isinstance(result.type, ArrowIntervalType) assert result.type.closed == arr.closed assert result.type.subtype == pa.float64() # fields have missing values (not NaN) left = pa.array([0.0, None, 2.0], type="float64") right = pa.array([1.0, None, 3.0], type="float64") assert result.storage.field("left").equals(left) assert result.storage.field("right").equals(right) # structarray itself also has missing values on the array level vals = [ {"left": 0.0, "right": 1.0}, {"left": None, "right": None}, {"left": 2.0, "right": 3.0}, ] expected = pa.StructArray.from_pandas(vals, mask=np.array([False, True, False])) assert result.storage.equals(expected)
def test_index_series_compat(self, op, constructor, expected_type, assert_func): # IntervalIndex/Series that rely on IntervalArray for comparisons breaks = range(4) index = constructor(IntervalIndex.from_breaks(breaks)) # scalar comparisons other = index[0] result = op(index, other) expected = expected_type(self.elementwise_comparison(op, index, other)) assert_func(result, expected) other = breaks[0] result = op(index, other) expected = expected_type(self.elementwise_comparison(op, index, other)) assert_func(result, expected) # list-like comparisons other = IntervalArray.from_breaks(breaks) result = op(index, other) expected = expected_type(self.elementwise_comparison(op, index, other)) assert_func(result, expected) other = [index[0], breaks[0], "foo"] result = op(index, other) expected = expected_type(self.elementwise_comparison(op, index, other)) assert_func(result, expected)
def test_compare_scalar_interval_mixed_closed(self, op, closed, other_closed): interval_array = IntervalArray.from_arrays(range(2), range(1, 3), closed=closed) other = Interval(0, 1, closed=other_closed) result = op(interval_array, other) expected = self.elementwise_comparison(op, interval_array, other) tm.assert_numpy_array_equal(result, expected)
def test_arrow_table_roundtrip(breaks): import pyarrow as pa from pandas.core.arrays.arrow._arrow_utils import ArrowIntervalType arr = IntervalArray.from_breaks(breaks) arr[1] = None df = pd.DataFrame({"a": arr}) table = pa.table(df) assert isinstance(table.field("a").type, ArrowIntervalType) result = table.to_pandas() assert isinstance(result["a"].dtype, pd.IntervalDtype) tm.assert_frame_equal(result, df) table2 = pa.concat_tables([table, table]) result = table2.to_pandas() expected = pd.concat([df, df], ignore_index=True) tm.assert_frame_equal(result, expected) # GH-41040 table = pa.table([pa.chunked_array([], type=table.column(0).type)], schema=table.schema) result = table.to_pandas() tm.assert_frame_equal(result, expected[0:0])
def test_set_na(self, left_right_dtypes): left, right = left_right_dtypes result = IntervalArray.from_arrays(left, right) if result.dtype.subtype.kind in ["i", "u"]: msg = "Cannot set float NaN to integer-backed IntervalArray" with pytest.raises(ValueError, match=msg): result[0] = np.NaN return result[0] = np.nan expected_left = Index([left._na_value] + list(left[1:])) expected_right = Index([right._na_value] + list(right[1:])) expected = IntervalArray.from_arrays(expected_left, expected_right) tm.assert_extension_array_equal(result, expected)
def test_repr(): # GH 25022 arr = IntervalArray.from_tuples([(0, 1), (1, 2)]) result = repr(arr) expected = ("<IntervalArray>\n" "[(0, 1], (1, 2]]\n" "Length: 2, dtype: interval[int64, right]") assert result == expected
def test_compare_list_like_interval_mixed_closed( self, op, interval_constructor, closed, other_closed ): interval_array = IntervalArray.from_arrays(range(2), range(1, 3), closed=closed) other = interval_constructor(range(2), range(1, 3), closed=other_closed) result = op(interval_array, other) expected = self.elementwise_comparison(op, interval_array, other) tm.assert_equal(result, expected)
def __from_arrow__(self, array): """Construct IntervalArray from pyarrow Array/ChunkedArray.""" import pyarrow from pandas.core.arrays import IntervalArray if isinstance(array, pyarrow.Array): chunks = [array] else: chunks = array.chunks results = [] for arr in chunks: left = np.asarray(arr.storage.field("left"), dtype=self.subtype) right = np.asarray(arr.storage.field("right"), dtype=self.subtype) iarr = IntervalArray.from_arrays(left, right, closed=array.type.closed) results.append(iarr) return IntervalArray._concat_same_type(results)
def test_shift_datetime(self): a = IntervalArray.from_breaks(pd.date_range("2000", periods=4)) result = a.shift(2) expected = a.take([-1, -1, 0], allow_fill=True) tm.assert_interval_array_equal(result, expected) result = a.shift(-1) expected = a.take([1, 2, -1], allow_fill=True) tm.assert_interval_array_equal(result, expected)
def test_get_numeric_data_extension_dtype(self): # GH 22290 df = DataFrame({ 'A': integer_array([-10, np.nan, 0, 10, 20, 30], dtype='Int64'), 'B': Categorical(list('abcabc')), 'C': integer_array([0, 1, 2, 3, np.nan, 5], dtype='UInt8'), 'D': IntervalArray.from_breaks(range(7))}) result = df._get_numeric_data() expected = df.loc[:, ['A', 'C']] assert_frame_equal(result, expected)
def test_get_numeric_data_extension_dtype(self): # GH 22290 df = DataFrame({ 'A': integer_array([-10, np.nan, 0, 10, 20, 30], dtype='Int64'), 'B': Categorical(list('abcabc')), 'C': integer_array([0, 1, 2, 3, np.nan, 5], dtype='UInt8'), 'D': IntervalArray.from_breaks(range(7))}) result = df._get_numeric_data() expected = df.loc[:, ['A', 'C']] assert_frame_equal(result, expected)
def test_dtype_closed_mismatch(): # GH#38394 closed specified in both dtype and IntervalIndex constructor dtype = IntervalDtype(np.int64, "left") msg = "closed keyword does not match dtype.closed" with pytest.raises(ValueError, match=msg): IntervalIndex([], dtype=dtype, closed="neither") with pytest.raises(ValueError, match=msg): IntervalArray([], dtype=dtype, closed="neither")
def test_where_raises(self, other): # GH#45768 The IntervalArray methods raises; the Series method coerces ser = pd.Series(IntervalArray.from_breaks([1, 2, 3, 4], closed="left")) mask = np.array([True, False, True]) match = "'value.closed' is 'right', expected 'left'." with pytest.raises(ValueError, match=match): ser.array._where(mask, other) res = ser.where(mask, other=other) expected = ser.astype(object).where(mask, other) tm.assert_series_equal(res, expected)
def test_dtype_inclusive_mismatch(): # GH#38394 dtype = IntervalDtype(np.int64, "left") msg = "inclusive keyword does not match dtype.inclusive" with pytest.raises(ValueError, match=msg): IntervalIndex([], dtype=dtype, inclusive="neither") with pytest.raises(ValueError, match=msg): IntervalArray([], dtype=dtype, inclusive="neither")
def test_get_numeric_data_extension_dtype(self): # GH 22290 df = DataFrame( { "A": integer_array([-10, np.nan, 0, 10, 20, 30], dtype="Int64"), "B": Categorical(list("abcabc")), "C": integer_array([0, 1, 2, 3, np.nan, 5], dtype="UInt8"), "D": IntervalArray.from_breaks(range(7)), } ) result = df._get_numeric_data() expected = df.loc[:, ["A", "C"]] assert_frame_equal(result, expected)
def test_setitem_empty_indexer(self, data, box_in_series): data_dtype = type(data) if box_in_series: data = pd.Series(data) original = data.copy() if data_dtype == IntervalArray: data[np.array([], dtype=int)] = IntervalArray([], "right") else: data[np.array([], dtype=int)] = [] self.assert_equal(data, original)
def test_set_na(self, left_right_dtypes): left, right = left_right_dtypes left = left.copy(deep=True) right = right.copy(deep=True) result = IntervalArray.from_arrays(left, right) if result.dtype.subtype.kind not in ["m", "M"]: msg = "'value' should be an interval type, got <.*NaTType'> instead." with pytest.raises(TypeError, match=msg): result[0] = pd.NaT if result.dtype.subtype.kind in ["i", "u"]: msg = "Cannot set float NaN to integer-backed IntervalArray" with pytest.raises(ValueError, match=msg): result[0] = np.NaN return result[0] = np.nan expected_left = Index([left._na_value] + list(left[1:])) expected_right = Index([right._na_value] + list(right[1:])) expected = IntervalArray.from_arrays(expected_left, expected_right) tm.assert_extension_array_equal(result, expected)
class TestMethods: @pytest.mark.parametrize("new_inclusive", ["left", "right", "both", "neither"]) def test_set_inclusive(self, closed, new_inclusive): # GH 21670 array = IntervalArray.from_breaks(range(10), inclusive=closed) result = array.set_inclusive(new_inclusive) expected = IntervalArray.from_breaks(range(10), inclusive=new_inclusive) tm.assert_extension_array_equal(result, expected) @pytest.mark.parametrize( "other", [ Interval(0, 1, inclusive="right"), IntervalArray.from_breaks([1, 2, 3, 4], inclusive="right"), ], ) def test_where_raises(self, other): # GH#45768 The IntervalArray methods raises; the Series method coerces ser = pd.Series( IntervalArray.from_breaks([1, 2, 3, 4], inclusive="left")) mask = np.array([True, False, True]) match = "'value.inclusive' is 'right', expected 'left'." with pytest.raises(ValueError, match=match): ser.array._where(mask, other) res = ser.where(mask, other=other) expected = ser.astype(object).where(mask, other) tm.assert_series_equal(res, expected) def test_shift(self): # https://github.com/pandas-dev/pandas/issues/31495, GH#22428, GH#31502 a = IntervalArray.from_breaks([1, 2, 3], "right") result = a.shift() # int -> float expected = IntervalArray.from_tuples([(np.nan, np.nan), (1.0, 2.0)], "right") tm.assert_interval_array_equal(result, expected) def test_shift_datetime(self): # GH#31502, GH#31504 a = IntervalArray.from_breaks(date_range("2000", periods=4), "right") result = a.shift(2) expected = a.take([-1, -1, 0], allow_fill=True) tm.assert_interval_array_equal(result, expected) result = a.shift(-1) expected = a.take([1, 2, -1], allow_fill=True) tm.assert_interval_array_equal(result, expected)
def test_setitem_mismatched_inclusive(self): arr = IntervalArray.from_breaks(range(4), "right") orig = arr.copy() other = arr.set_inclusive("both") msg = "'value.inclusive' is 'both', expected 'right'" with pytest.raises(ValueError, match=msg): arr[0] = other[0] with pytest.raises(ValueError, match=msg): arr[:1] = other[:1] with pytest.raises(ValueError, match=msg): arr[:0] = other[:0] with pytest.raises(ValueError, match=msg): arr[:] = other[::-1] with pytest.raises(ValueError, match=msg): arr[:] = list(other[::-1]) with pytest.raises(ValueError, match=msg): arr[:] = other[::-1].astype(object) with pytest.raises(ValueError, match=msg): arr[:] = other[::-1].astype("category") # empty list should be no-op arr[:0] = IntervalArray.from_breaks([], "right") tm.assert_interval_array_equal(arr, orig)
def test_arrow_table_roundtrip_without_metadata(breaks): import pyarrow as pa arr = IntervalArray.from_breaks(breaks) arr[1] = None df = pd.DataFrame({"a": arr}) table = pa.table(df) # remove the metadata table = table.replace_schema_metadata() assert table.schema.metadata is None result = table.to_pandas() assert isinstance(result["a"].dtype, pd.IntervalDtype) tm.assert_frame_equal(result, df)
def test_from_arrow_from_raw_struct_array(): # in case pyarrow lost the Interval extension type (eg on parquet roundtrip # with datetime64[ns] subtype, see GH-45881), still allow conversion # from arrow to IntervalArray import pyarrow as pa arr = pa.array([{"left": 0, "right": 1}, {"left": 1, "right": 2}]) dtype = pd.IntervalDtype(np.dtype("int64"), closed="neither") result = dtype.__from_arrow__(arr) expected = IntervalArray.from_breaks(np.array([0, 1, 2], dtype="int64"), closed="neither") tm.assert_extension_array_equal(result, expected) result = dtype.__from_arrow__(pa.chunked_array([arr])) tm.assert_extension_array_equal(result, expected)
def test_min_max_invalid_axis(self, left_right_dtypes): left, right = left_right_dtypes left = left.copy(deep=True) right = right.copy(deep=True) arr = IntervalArray.from_arrays(left, right) msg = "`axis` must be fewer than the number of dimensions" for axis in [-2, 1]: with pytest.raises(ValueError, match=msg): arr.min(axis=axis) with pytest.raises(ValueError, match=msg): arr.max(axis=axis) msg = "'>=' not supported between" with pytest.raises(TypeError, match=msg): arr.min(axis="foo") with pytest.raises(TypeError, match=msg): arr.max(axis="foo")
class TestMethods: @pytest.mark.parametrize('new_closed', ['left', 'right', 'both', 'neither']) def test_set_closed(self, closed, new_closed): # GH 21670 array = IntervalArray.from_breaks(range(10), closed=closed) result = array.set_closed(new_closed) expected = IntervalArray.from_breaks(range(10), closed=new_closed) tm.assert_extension_array_equal(result, expected) @pytest.mark.parametrize('other', [ Interval(0, 1, closed='right'), IntervalArray.from_breaks([1, 2, 3, 4], closed='right'), ]) def test_where_raises(self, other): ser = pd.Series(IntervalArray.from_breaks([1, 2, 3, 4], closed='left')) match = "'value.closed' is 'right', expected 'left'." with pytest.raises(ValueError, match=match): ser.where([True, False, True], other=other)
def test_min_max(self, left_right_dtypes, index_or_series_or_array): # GH#44746 left, right = left_right_dtypes left = left.copy(deep=True) right = right.copy(deep=True) arr = IntervalArray.from_arrays(left, right) # The expected results below are only valid if monotonic assert left.is_monotonic_increasing assert Index(arr).is_monotonic_increasing MIN = arr[0] MAX = arr[-1] indexer = np.arange(len(arr)) np.random.shuffle(indexer) arr = arr.take(indexer) arr_na = arr.insert(2, np.nan) arr = index_or_series_or_array(arr) arr_na = index_or_series_or_array(arr_na) for skipna in [True, False]: res = arr.min(skipna=skipna) assert res == MIN assert type(res) == type(MIN) res = arr.max(skipna=skipna) assert res == MAX assert type(res) == type(MAX) res = arr_na.min(skipna=False) assert np.isnan(res) res = arr_na.max(skipna=False) assert np.isnan(res) res = arr_na.min(skipna=True) assert res == MIN assert type(res) == type(MIN) res = arr_na.max(skipna=True) assert res == MAX assert type(res) == type(MAX)
class TestMethods: @pytest.mark.parametrize("new_closed", ["left", "right", "both", "neither"]) def test_set_closed(self, closed, new_closed): # GH 21670 array = IntervalArray.from_breaks(range(10), closed=closed) result = array.set_closed(new_closed) expected = IntervalArray.from_breaks(range(10), closed=new_closed) tm.assert_extension_array_equal(result, expected) @pytest.mark.parametrize( "other", [ Interval(0, 1, closed="right"), IntervalArray.from_breaks([1, 2, 3, 4], closed="right"), ], ) def test_where_raises(self, other): ser = pd.Series(IntervalArray.from_breaks([1, 2, 3, 4], closed="left")) match = "'value.closed' is 'right', expected 'left'." with pytest.raises(ValueError, match=match): ser.where([True, False, True], other=other) def test_shift(self): # https://github.com/pandas-dev/pandas/issues/31495, GH#22428, GH#31502 a = IntervalArray.from_breaks([1, 2, 3]) result = a.shift() # int -> float expected = IntervalArray.from_tuples([(np.nan, np.nan), (1.0, 2.0)]) tm.assert_interval_array_equal(result, expected) def test_shift_datetime(self): # GH#31502, GH#31504 a = IntervalArray.from_breaks(date_range("2000", periods=4)) result = a.shift(2) expected = a.take([-1, -1, 0], allow_fill=True) tm.assert_interval_array_equal(result, expected) result = a.shift(-1) expected = a.take([1, 2, -1], allow_fill=True) tm.assert_interval_array_equal(result, expected)
class TestMethods(object): @pytest.mark.parametrize('repeats', [0, 1, 5]) def test_repeat(self, left_right_dtypes, repeats): left, right = left_right_dtypes result = IntervalArray.from_arrays(left, right).repeat(repeats) expected = IntervalArray.from_arrays(left.repeat(repeats), right.repeat(repeats)) tm.assert_extension_array_equal(result, expected) @pytest.mark.parametrize( 'bad_repeats, msg', [(-1, 'negative dimensions are not allowed'), ('foo', r'invalid literal for (int|long)\(\) with base 10')]) def test_repeat_errors(self, bad_repeats, msg): array = IntervalArray.from_breaks(range(4)) with pytest.raises(ValueError, match=msg): array.repeat(bad_repeats) @pytest.mark.parametrize('new_closed', ['left', 'right', 'both', 'neither']) def test_set_closed(self, closed, new_closed): # GH 21670 array = IntervalArray.from_breaks(range(10), closed=closed) result = array.set_closed(new_closed) expected = IntervalArray.from_breaks(range(10), closed=new_closed) tm.assert_extension_array_equal(result, expected) @pytest.mark.parametrize('other', [ Interval(0, 1, closed='right'), IntervalArray.from_breaks([1, 2, 3, 4], closed='right'), ]) def test_where_raises(self, other): ser = pd.Series(IntervalArray.from_breaks([1, 2, 3, 4], closed='left')) match = "'value.closed' is 'right', expected 'left'." with pytest.raises(ValueError, match=match): ser.where([True, False, True], other=other)
def test_repeat(self, left_right_dtypes, repeats): left, right = left_right_dtypes result = IntervalArray.from_arrays(left, right).repeat(repeats) expected = IntervalArray.from_arrays( left.repeat(repeats), right.repeat(repeats)) tm.assert_extension_array_equal(result, expected)
def test_repeat_errors(self, bad_repeats, msg): array = IntervalArray.from_breaks(range(4)) with pytest.raises(ValueError, match=msg): array.repeat(bad_repeats)
def test_where_raises(self, other): ser = pd.Series(IntervalArray.from_breaks([1, 2, 3, 4], closed='left')) match = "'value.closed' is 'right', expected 'left'." with pytest.raises(ValueError, match=match): ser.where([True, False, True], other=other)
def array( data: Union[Sequence[object], AnyArrayLike], dtype: Optional[Dtype] = None, copy: bool = True, ) -> "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.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> ['0 days 01:00:00', '0 days 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, <NA>] Length: 3, dtype: Int64 >>> pd.array(["a", None, "c"]) <StringArray> ['a', <NA>, '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 data_for_sorting(): return IntervalArray.from_tuples([(1, 2), (2, 3), (0, 1)])
def data_missing_for_sorting(): return IntervalArray.from_tuples([(1, 2), None, (0, 1)])
def data_for_grouping(): a = (0, 1) b = (1, 2) c = (2, 3) return IntervalArray.from_tuples([b, b, None, None, a, a, b, c])
def test_repeat_errors(self, bad_repeats, msg): array = IntervalArray.from_breaks(range(4)) with tm.assert_raises_regex(ValueError, msg): array.repeat(bad_repeats)
result = ser.array if is_datetime64_dtype(any_numpy_dtype): assert isinstance(result, DatetimeArray) elif is_timedelta64_dtype(any_numpy_dtype): assert isinstance(result, TimedeltaArray) else: assert isinstance(result, PandasArray) @pytest.mark.parametrize( "array, attr", [ (pd.Categorical(["a", "b"]), "_codes"), (pd.core.arrays.period_array(["2000", "2001"], freq="D"), "_data"), (pd.core.arrays.integer_array([0, np.nan]), "_data"), (IntervalArray.from_breaks([0, 1]), "_left"), (SparseArray([0, 1]), "_sparse_values"), (DatetimeArray(np.array([1, 2], dtype="datetime64[ns]")), "_data"), # tz-aware Datetime ( DatetimeArray( np.array(["2000-01-01T12:00:00", "2000-01-02T12:00:00"], dtype="M8[ns]"), dtype=DatetimeTZDtype(tz="US/Central"), ), "_data", ), ], ) def test_array(array, attr, index_or_series): box = index_or_series
def data_missing(): """Length 2 array with [NA, Valid]""" return IntervalArray.from_tuples([None, (0, 1)])
def test_compare_length_mismatch_errors(self, op, other_constructor, length): array = IntervalArray.from_arrays(range(4), range(1, 5)) other = other_constructor([Interval(0, 1)] * length) with pytest.raises(ValueError, match="Lengths must match to compare"): op(array, other)
def array(left_right_dtypes): """ Fixture to generate an IntervalArray of various dtypes containing NA if possible """ left, right = left_right_dtypes return IntervalArray.from_arrays(left, right)
def create_series_intervals(left, right, closed="right"): return Series(IntervalArray.from_arrays(left, right, closed))
def test_set_closed(self, closed, new_closed): # GH 21670 array = IntervalArray.from_breaks(range(10), closed=closed) result = array.set_closed(new_closed) expected = IntervalArray.from_breaks(range(10), closed=new_closed) tm.assert_extension_array_equal(result, expected)