738 lines
23 KiB
Python
738 lines
23 KiB
Python
import datetime
|
|
import decimal
|
|
import zoneinfo
|
|
|
|
import numpy as np
|
|
from numpy import ma
|
|
import pytest
|
|
|
|
from pandas._config import using_string_dtype
|
|
|
|
import pandas.util._test_decorators as td
|
|
|
|
import pandas as pd
|
|
import pandas._testing as tm
|
|
from pandas.api.extensions import register_extension_dtype
|
|
from pandas.arrays import (
|
|
BooleanArray,
|
|
DatetimeArray,
|
|
FloatingArray,
|
|
IntegerArray,
|
|
IntervalArray,
|
|
NumpyExtensionArray,
|
|
SparseArray,
|
|
TimedeltaArray,
|
|
)
|
|
from pandas.tests.extension.decimal import (
|
|
DecimalArray,
|
|
DecimalDtype,
|
|
to_decimal,
|
|
)
|
|
|
|
|
|
@pytest.mark.parametrize("dtype_unit", ["M8[h]", "M8[m]", "m8[h]"])
|
|
def test_dt64_array(dtype_unit):
|
|
# GH#53817
|
|
dtype_var = np.dtype(dtype_unit)
|
|
msg = (
|
|
r"datetime64 and timedelta64 dtype resolutions other than "
|
|
r"'s', 'ms', 'us', and 'ns' are no longer supported."
|
|
)
|
|
with pytest.raises(ValueError, match=msg):
|
|
pd.array([], dtype=dtype_var)
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"data, dtype, expected",
|
|
[
|
|
# Basic NumPy defaults.
|
|
([], None, FloatingArray._from_sequence([], dtype="Float64")),
|
|
([1, 2], None, IntegerArray._from_sequence([1, 2], dtype="Int64")),
|
|
([1, 2], object, NumpyExtensionArray(np.array([1, 2], dtype=object))),
|
|
(
|
|
[1, 2],
|
|
np.dtype("float32"),
|
|
NumpyExtensionArray(np.array([1.0, 2.0], dtype=np.dtype("float32"))),
|
|
),
|
|
(
|
|
np.array([], dtype=object),
|
|
None,
|
|
NumpyExtensionArray(np.array([], dtype=object)),
|
|
),
|
|
(
|
|
np.array([1, 2], dtype="int64"),
|
|
None,
|
|
IntegerArray._from_sequence([1, 2], dtype="Int64"),
|
|
),
|
|
(
|
|
np.array([1.0, 2.0], dtype="float64"),
|
|
None,
|
|
FloatingArray._from_sequence([1.0, 2.0], dtype="Float64"),
|
|
),
|
|
# String alias passes through to NumPy
|
|
([1, 2], "float32", NumpyExtensionArray(np.array([1, 2], dtype="float32"))),
|
|
([1, 2], "int64", NumpyExtensionArray(np.array([1, 2], dtype=np.int64))),
|
|
# GH#44715 FloatingArray does not support float16, so fall
|
|
# back to NumpyExtensionArray
|
|
(
|
|
np.array([1, 2], dtype=np.float16),
|
|
None,
|
|
NumpyExtensionArray(np.array([1, 2], dtype=np.float16)),
|
|
),
|
|
# idempotency with e.g. pd.array(pd.array([1, 2], dtype="int64"))
|
|
(
|
|
NumpyExtensionArray(np.array([1, 2], dtype=np.int32)),
|
|
None,
|
|
NumpyExtensionArray(np.array([1, 2], dtype=np.int32)),
|
|
),
|
|
# Period alias
|
|
(
|
|
[pd.Period("2000", "D"), pd.Period("2001", "D")],
|
|
"Period[D]",
|
|
pd.PeriodIndex(["2000", "2001"], freq="D").array,
|
|
),
|
|
# Period dtype
|
|
(
|
|
[pd.Period("2000", "D")],
|
|
pd.PeriodDtype("D"),
|
|
pd.PeriodIndex(["2000"], freq="D").array,
|
|
),
|
|
# Datetime (naive)
|
|
(
|
|
[1, 2],
|
|
np.dtype("datetime64[ns]"),
|
|
DatetimeArray._from_sequence(
|
|
np.array([1, 2], dtype="M8[ns]"), dtype="M8[ns]"
|
|
),
|
|
),
|
|
(
|
|
[1, 2],
|
|
np.dtype("datetime64[s]"),
|
|
DatetimeArray._from_sequence(
|
|
np.array([1, 2], dtype="M8[s]"), dtype="M8[s]"
|
|
),
|
|
),
|
|
(
|
|
np.array([1, 2], dtype="datetime64[ns]"),
|
|
None,
|
|
DatetimeArray._from_sequence(
|
|
np.array([1, 2], dtype="M8[ns]"), dtype="M8[ns]"
|
|
),
|
|
),
|
|
(
|
|
pd.DatetimeIndex(["2000", "2001"]),
|
|
np.dtype("datetime64[ns]"),
|
|
DatetimeArray._from_sequence(["2000", "2001"], dtype="M8[ns]"),
|
|
),
|
|
(
|
|
pd.DatetimeIndex(["2000", "2001"]),
|
|
None,
|
|
DatetimeArray._from_sequence(["2000", "2001"], dtype="M8[us]"),
|
|
),
|
|
(
|
|
["2000", "2001"],
|
|
np.dtype("datetime64[ns]"),
|
|
DatetimeArray._from_sequence(["2000", "2001"], dtype="M8[ns]"),
|
|
),
|
|
(
|
|
[pd.NaT, pd.NaT],
|
|
None,
|
|
DatetimeArray._from_sequence([pd.NaT, pd.NaT], dtype="M8[s]"),
|
|
),
|
|
# Datetime (tz-aware)
|
|
(
|
|
["2000", "2001"],
|
|
pd.DatetimeTZDtype(tz="CET"),
|
|
DatetimeArray._from_sequence(
|
|
["2000", "2001"], dtype=pd.DatetimeTZDtype(tz="CET")
|
|
),
|
|
),
|
|
# Timedelta
|
|
(
|
|
["1h", "2h"],
|
|
np.dtype("timedelta64[ns]"),
|
|
TimedeltaArray._from_sequence(["1h", "2h"], dtype="m8[ns]"),
|
|
),
|
|
(
|
|
pd.TimedeltaIndex(["1h", "2h"]),
|
|
np.dtype("timedelta64[ns]"),
|
|
TimedeltaArray._from_sequence(["1h", "2h"], dtype="m8[ns]"),
|
|
),
|
|
(
|
|
np.array([1, 2], dtype="m8[s]"),
|
|
np.dtype("timedelta64[s]"),
|
|
TimedeltaArray._from_sequence(
|
|
np.array([1, 2], dtype="m8[s]"), dtype="m8[s]"
|
|
),
|
|
),
|
|
(
|
|
pd.TimedeltaIndex(["1h", "2h"]),
|
|
None,
|
|
TimedeltaArray._from_sequence(["1h", "2h"], dtype="m8[us]"),
|
|
),
|
|
(
|
|
# preserve non-nano, i.e. don't cast to NumpyExtensionArray
|
|
TimedeltaArray._simple_new(
|
|
np.arange(5, dtype=np.int64).view("m8[s]"), dtype=np.dtype("m8[s]")
|
|
),
|
|
None,
|
|
TimedeltaArray._simple_new(
|
|
np.arange(5, dtype=np.int64).view("m8[s]"), dtype=np.dtype("m8[s]")
|
|
),
|
|
),
|
|
(
|
|
# preserve non-nano, i.e. don't cast to NumpyExtensionArray
|
|
TimedeltaArray._simple_new(
|
|
np.arange(5, dtype=np.int64).view("m8[s]"), dtype=np.dtype("m8[s]")
|
|
),
|
|
np.dtype("m8[s]"),
|
|
TimedeltaArray._simple_new(
|
|
np.arange(5, dtype=np.int64).view("m8[s]"), dtype=np.dtype("m8[s]")
|
|
),
|
|
),
|
|
# Category
|
|
(["a", "b"], "category", pd.Categorical(["a", "b"])),
|
|
(
|
|
["a", "b"],
|
|
pd.CategoricalDtype(None, ordered=True),
|
|
pd.Categorical(["a", "b"], ordered=True),
|
|
),
|
|
# Interval
|
|
(
|
|
[pd.Interval(1, 2), pd.Interval(3, 4)],
|
|
"interval",
|
|
IntervalArray.from_tuples([(1, 2), (3, 4)]),
|
|
),
|
|
# Sparse
|
|
([0, 1], "Sparse[int64]", SparseArray([0, 1], dtype="int64")),
|
|
# IntegerNA
|
|
([1, None], "Int16", pd.array([1, None], dtype="Int16")),
|
|
(
|
|
pd.Series([1, 2]),
|
|
None,
|
|
NumpyExtensionArray(np.array([1, 2], dtype=np.int64)),
|
|
),
|
|
# String
|
|
(
|
|
["a", None],
|
|
"string",
|
|
pd.StringDtype()
|
|
.construct_array_type()
|
|
._from_sequence(["a", None], dtype=pd.StringDtype()),
|
|
),
|
|
(
|
|
["a", None],
|
|
"str",
|
|
pd.StringDtype(na_value=np.nan)
|
|
.construct_array_type()
|
|
._from_sequence(["a", None], dtype=pd.StringDtype(na_value=np.nan))
|
|
if using_string_dtype()
|
|
else NumpyExtensionArray(np.array(["a", "None"])),
|
|
),
|
|
(
|
|
["a", None],
|
|
pd.StringDtype(),
|
|
pd.StringDtype()
|
|
.construct_array_type()
|
|
._from_sequence(["a", None], dtype=pd.StringDtype()),
|
|
),
|
|
(
|
|
["a", None],
|
|
pd.StringDtype(na_value=np.nan),
|
|
pd.StringDtype(na_value=np.nan)
|
|
.construct_array_type()
|
|
._from_sequence(["a", None], dtype=pd.StringDtype(na_value=np.nan)),
|
|
),
|
|
(
|
|
# numpy array with string dtype
|
|
np.array(["a", "b"], dtype=str),
|
|
pd.StringDtype(),
|
|
pd.StringDtype()
|
|
.construct_array_type()
|
|
._from_sequence(["a", "b"], dtype=pd.StringDtype()),
|
|
),
|
|
(
|
|
# numpy array with string dtype
|
|
np.array(["a", "b"], dtype=str),
|
|
pd.StringDtype(na_value=np.nan),
|
|
pd.StringDtype(na_value=np.nan)
|
|
.construct_array_type()
|
|
._from_sequence(["a", "b"], dtype=pd.StringDtype(na_value=np.nan)),
|
|
),
|
|
# Boolean
|
|
(
|
|
[True, None],
|
|
"boolean",
|
|
BooleanArray._from_sequence([True, None], dtype="boolean"),
|
|
),
|
|
(
|
|
[True, None],
|
|
pd.BooleanDtype(),
|
|
BooleanArray._from_sequence([True, None], dtype="boolean"),
|
|
),
|
|
# Index
|
|
(pd.Index([1, 2]), None, NumpyExtensionArray(np.array([1, 2], dtype=np.int64))),
|
|
# Series[EA] returns the EA
|
|
(
|
|
pd.Series(pd.Categorical(["a", "b"], categories=["a", "b", "c"])),
|
|
None,
|
|
pd.Categorical(["a", "b"], categories=["a", "b", "c"]),
|
|
),
|
|
# "3rd party" EAs work
|
|
([decimal.Decimal(0), decimal.Decimal(1)], "decimal", to_decimal([0, 1])),
|
|
# pass an ExtensionArray, but a different dtype
|
|
(
|
|
pd.PeriodIndex(["2000", "2001"], freq="D").array,
|
|
"category",
|
|
pd.Categorical([pd.Period("2000", "D"), pd.Period("2001", "D")]),
|
|
),
|
|
# Complex
|
|
(
|
|
np.array([complex(1), complex(2)], dtype=np.complex128),
|
|
None,
|
|
NumpyExtensionArray(
|
|
np.array([complex(1), complex(2)], dtype=np.complex128)
|
|
),
|
|
),
|
|
],
|
|
)
|
|
def test_array(data, dtype, expected):
|
|
result = pd.array(data, dtype=dtype)
|
|
tm.assert_equal(result, expected)
|
|
|
|
|
|
def test_array_copy():
|
|
a = np.array([1, 2])
|
|
# default is to copy
|
|
b = pd.array(a, dtype=a.dtype)
|
|
assert not tm.shares_memory(a, b)
|
|
|
|
# copy=True
|
|
b = pd.array(a, dtype=a.dtype, copy=True)
|
|
assert not tm.shares_memory(a, b)
|
|
|
|
# copy=False
|
|
b = pd.array(a, dtype=a.dtype, copy=False)
|
|
assert tm.shares_memory(a, b)
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"data",
|
|
[
|
|
# string 2D
|
|
[["a"], ["b"]],
|
|
# int 2D
|
|
[[1], [2]],
|
|
# mixed 2D
|
|
[[1, 2], ["a", "b"]],
|
|
# mixed 3D
|
|
[[[1]], [["a"]], [[3.14]]],
|
|
],
|
|
)
|
|
def test_array_string_nd(data):
|
|
# GH 64138
|
|
result = pd.array(data, dtype="str")
|
|
|
|
if using_string_dtype():
|
|
expected = (
|
|
pd.StringDtype(na_value=np.nan)
|
|
.construct_array_type()
|
|
._from_sequence(data, dtype=pd.StringDtype(na_value=np.nan))
|
|
)
|
|
else:
|
|
expected = NumpyExtensionArray(np.array(data, dtype=str))
|
|
|
|
tm.assert_equal(result, expected)
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"data, expected",
|
|
[
|
|
# period
|
|
(
|
|
[pd.Period("2000", "D"), pd.Period("2001", "D")],
|
|
pd.PeriodIndex(["2000", "2001"], freq="D").array,
|
|
),
|
|
# interval
|
|
([pd.Interval(0, 1), pd.Interval(1, 2)], IntervalArray.from_breaks([0, 1, 2])),
|
|
# datetime
|
|
(
|
|
[pd.Timestamp("2000").as_unit("s"), pd.Timestamp("2001").as_unit("s")],
|
|
DatetimeArray._from_sequence(["2000", "2001"], dtype="M8[s]"),
|
|
),
|
|
(
|
|
[datetime.datetime(2000, 1, 1), datetime.datetime(2001, 1, 1)],
|
|
DatetimeArray._from_sequence(["2000", "2001"], dtype="M8[us]"),
|
|
),
|
|
(
|
|
np.array([1, 2], dtype="M8[ns]"),
|
|
DatetimeArray._from_sequence(np.array([1, 2], dtype="M8[ns]")),
|
|
),
|
|
(
|
|
np.array([1, 2], dtype="M8[us]"),
|
|
DatetimeArray._simple_new(
|
|
np.array([1, 2], dtype="M8[us]"), dtype=np.dtype("M8[us]")
|
|
),
|
|
),
|
|
# datetimetz
|
|
(
|
|
[
|
|
pd.Timestamp("2000", tz="CET").as_unit("s"),
|
|
pd.Timestamp("2001", tz="CET").as_unit("s"),
|
|
],
|
|
DatetimeArray._from_sequence(
|
|
["2000", "2001"], dtype=pd.DatetimeTZDtype(tz="CET", unit="s")
|
|
),
|
|
),
|
|
(
|
|
[
|
|
datetime.datetime(
|
|
2000, 1, 1, tzinfo=zoneinfo.ZoneInfo("Europe/Berlin")
|
|
),
|
|
datetime.datetime(
|
|
2001, 1, 1, tzinfo=zoneinfo.ZoneInfo("Europe/Berlin")
|
|
),
|
|
],
|
|
DatetimeArray._from_sequence(
|
|
["2000", "2001"],
|
|
dtype=pd.DatetimeTZDtype(
|
|
tz=zoneinfo.ZoneInfo("Europe/Berlin"), unit="us"
|
|
),
|
|
),
|
|
),
|
|
# timedelta
|
|
(
|
|
[pd.Timedelta("1h"), pd.Timedelta("2h")],
|
|
TimedeltaArray._from_sequence(["1h", "2h"], dtype="m8[us]"),
|
|
),
|
|
(
|
|
np.array([1, 2], dtype="m8[ns]"),
|
|
TimedeltaArray._from_sequence(
|
|
np.array([1, 2], dtype="m8[ns]"), dtype=np.dtype("m8[ns]")
|
|
),
|
|
),
|
|
(
|
|
np.array([1, 2], dtype="m8[us]"),
|
|
TimedeltaArray._from_sequence(
|
|
np.array([1, 2], dtype="m8[us]"), dtype=np.dtype("m8[us]")
|
|
),
|
|
),
|
|
# integer
|
|
([1, 2], IntegerArray._from_sequence([1, 2], dtype="Int64")),
|
|
([1, None], IntegerArray._from_sequence([1, None], dtype="Int64")),
|
|
([1, pd.NA], IntegerArray._from_sequence([1, pd.NA], dtype="Int64")),
|
|
([1, np.nan], IntegerArray._from_sequence([1, pd.NA], dtype="Int64")),
|
|
# float
|
|
([0.1, 0.2], FloatingArray._from_sequence([0.1, 0.2], dtype="Float64")),
|
|
([0.1, None], FloatingArray._from_sequence([0.1, pd.NA], dtype="Float64")),
|
|
([0.1, np.nan], FloatingArray._from_sequence([0.1, pd.NA], dtype="Float64")),
|
|
([0.1, pd.NA], FloatingArray._from_sequence([0.1, pd.NA], dtype="Float64")),
|
|
# integer-like float
|
|
([1.0, 2.0], FloatingArray._from_sequence([1.0, 2.0], dtype="Float64")),
|
|
([1.0, None], FloatingArray._from_sequence([1.0, pd.NA], dtype="Float64")),
|
|
([1.0, np.nan], FloatingArray._from_sequence([1.0, pd.NA], dtype="Float64")),
|
|
([1.0, pd.NA], FloatingArray._from_sequence([1.0, pd.NA], dtype="Float64")),
|
|
# mixed-integer-float
|
|
([1, 2.0], FloatingArray._from_sequence([1.0, 2.0], dtype="Float64")),
|
|
(
|
|
[1, np.nan, 2.0],
|
|
FloatingArray._from_sequence([1.0, None, 2.0], dtype="Float64"),
|
|
),
|
|
# string
|
|
(
|
|
["a", "b"],
|
|
pd.StringDtype()
|
|
.construct_array_type()
|
|
._from_sequence(["a", "b"], dtype=pd.StringDtype()),
|
|
),
|
|
(
|
|
["a", None],
|
|
pd.StringDtype()
|
|
.construct_array_type()
|
|
._from_sequence(["a", None], dtype=pd.StringDtype()),
|
|
),
|
|
(
|
|
# numpy array with string dtype
|
|
np.array(["a", "b"], dtype=str),
|
|
pd.StringDtype()
|
|
.construct_array_type()
|
|
._from_sequence(["a", "b"], dtype=pd.StringDtype()),
|
|
),
|
|
# Boolean
|
|
([True, False], BooleanArray._from_sequence([True, False], dtype="boolean")),
|
|
([True, None], BooleanArray._from_sequence([True, None], dtype="boolean")),
|
|
],
|
|
)
|
|
def test_array_inference(data, expected):
|
|
result = pd.array(data)
|
|
tm.assert_equal(result, expected)
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"data",
|
|
[
|
|
# mix of frequencies
|
|
[pd.Period("2000", "D"), pd.Period("2001", "Y")],
|
|
# mix of closed
|
|
[pd.Interval(0, 1, closed="left"), pd.Interval(1, 2, closed="right")],
|
|
# Mix of timezones
|
|
[pd.Timestamp("2000", tz="CET"), pd.Timestamp("2000", tz="UTC")],
|
|
# Mix of tz-aware and tz-naive
|
|
[pd.Timestamp("2000", tz="CET"), pd.Timestamp("2000")],
|
|
np.array([pd.Timestamp("2000"), pd.Timestamp("2000", tz="CET")]),
|
|
],
|
|
)
|
|
def test_array_inference_fails(data):
|
|
result = pd.array(data)
|
|
expected = NumpyExtensionArray(np.array(data, dtype=object))
|
|
tm.assert_extension_array_equal(result, expected)
|
|
|
|
|
|
@pytest.mark.parametrize("data", [np.array(0)])
|
|
def test_nd_raises(data):
|
|
with pytest.raises(ValueError, match="NumpyExtensionArray must be 1-dimensional"):
|
|
pd.array(data, dtype="int64")
|
|
|
|
|
|
def test_scalar_raises():
|
|
with pytest.raises(ValueError, match="Cannot pass scalar '1'"):
|
|
pd.array(1)
|
|
|
|
|
|
@pytest.mark.parametrize("dtype", ["i8", "int64", "u8", "uint64"])
|
|
def test_pd_array_float_with_nan_to_integer_raises(dtype):
|
|
# GH#41724
|
|
arr = np.array([np.nan, 1.0])
|
|
msg = "Cannot convert non-finite values"
|
|
with pytest.raises(pd.errors.IntCastingNaNError, match=msg):
|
|
pd.array(arr, dtype=dtype)
|
|
|
|
|
|
def test_dataframe_raises():
|
|
# GH#51167 don't accidentally cast to StringArray by doing inference on columns
|
|
df = pd.DataFrame([[1, 2], [3, 4]], columns=["A", "B"])
|
|
msg = "Cannot pass DataFrame to 'pandas.array'"
|
|
with pytest.raises(TypeError, match=msg):
|
|
pd.array(df)
|
|
|
|
|
|
def test_bounds_check():
|
|
# GH21796
|
|
with pytest.raises(
|
|
TypeError, match=r"cannot safely cast non-equivalent int(32|64) to uint16"
|
|
):
|
|
pd.array([-1, 2, 3], dtype="UInt16")
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# A couple dummy classes to ensure that Series and Indexes are unboxed before
|
|
# getting to the EA classes.
|
|
|
|
|
|
@register_extension_dtype
|
|
class DecimalDtype2(DecimalDtype):
|
|
name = "decimal2"
|
|
|
|
def construct_array_type(self):
|
|
"""
|
|
Return the array type associated with this dtype.
|
|
|
|
Returns
|
|
-------
|
|
type
|
|
"""
|
|
return DecimalArray2
|
|
|
|
|
|
class DecimalArray2(DecimalArray):
|
|
@classmethod
|
|
def _from_sequence(cls, scalars, *, dtype=None, copy=False):
|
|
if isinstance(scalars, (pd.Series, pd.Index)):
|
|
raise TypeError("scalars should not be of type pd.Series or pd.Index")
|
|
|
|
return super()._from_sequence(scalars, dtype=dtype, copy=copy)
|
|
|
|
|
|
def test_array_unboxes(index_or_series):
|
|
box = index_or_series
|
|
|
|
data = box([decimal.Decimal("1"), decimal.Decimal("2")])
|
|
dtype = DecimalDtype2()
|
|
# make sure it works
|
|
with pytest.raises(
|
|
TypeError, match="scalars should not be of type pd.Series or pd.Index"
|
|
):
|
|
DecimalArray2._from_sequence(data, dtype=dtype)
|
|
|
|
result = pd.array(data, dtype="decimal2")
|
|
expected = DecimalArray2._from_sequence(data.values, dtype=dtype)
|
|
tm.assert_equal(result, expected)
|
|
|
|
|
|
def test_array_to_numpy_na():
|
|
# GH#40638
|
|
arr = pd.array([pd.NA, 1], dtype="string[python]")
|
|
result = arr.to_numpy(na_value=True, dtype=bool)
|
|
expected = np.array([True, True])
|
|
tm.assert_numpy_array_equal(result, expected)
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"data, mask",
|
|
[
|
|
([1, 2, 3], [False, True, False]),
|
|
([1, 2, 3], [False, False, False]),
|
|
([1, 2, 3], ma.nomask),
|
|
([], ma.nomask),
|
|
],
|
|
)
|
|
@pytest.mark.parametrize(
|
|
"np_dtype",
|
|
[
|
|
"uint8",
|
|
"int32",
|
|
"int64",
|
|
"bool",
|
|
"float16",
|
|
"float32",
|
|
"complex128",
|
|
"datetime64[ns]",
|
|
"timedelta64[ns]",
|
|
],
|
|
)
|
|
@pytest.mark.parametrize("copy", [True, False])
|
|
def test_masked_array_kinds(data, mask, np_dtype, copy):
|
|
# GH#63879
|
|
arr = np.array(data, dtype=np_dtype)
|
|
ma_arr = ma.array(arr, mask=mask)
|
|
result = pd.array(ma_arr, copy=copy)
|
|
expected = pd.array(arr)
|
|
if np.any(mask):
|
|
na = np.nan if np_dtype in ("float16", "complex128") else pd.NA
|
|
expected[np.asarray(mask)] = na
|
|
tm.assert_extension_array_equal(result, expected)
|
|
|
|
# Check whether we made a copy.
|
|
result_has_mask = np_dtype not in [
|
|
"float16",
|
|
"complex128",
|
|
"datetime64[ns]",
|
|
"timedelta64[ns]",
|
|
]
|
|
if result_has_mask:
|
|
result_data = result._data
|
|
else:
|
|
result_data = result._ndarray
|
|
|
|
expect_data_shares = not (
|
|
copy
|
|
# np.shares_memory is always False on length 0.
|
|
or len(ma_arr) == 0
|
|
# If the result has no mask, data needs to be modified if there are NA values
|
|
or (np.any(mask) and not result_has_mask)
|
|
)
|
|
assert np.shares_memory(result_data, ma_arr.data) == expect_data_shares
|
|
|
|
if not result_has_mask:
|
|
return
|
|
|
|
expect_mask_shares = not (copy or len(ma_arr) == 0 or mask is np.False_)
|
|
assert np.shares_memory(result._mask, ma_arr.mask) == expect_mask_shares
|
|
|
|
|
|
@pytest.mark.parametrize("dtype", [None, "Int64"])
|
|
def test_masked_array_no_float_detour(dtype):
|
|
# GH#63879 - ensure we don't round-trip through float64
|
|
ma_arr = ma.array([2**53 + 1, 2, 3], mask=[False, True, False], dtype=np.int64)
|
|
result = pd.array(ma_arr, dtype=dtype)
|
|
expected = pd.array([2**53 + 1, pd.NA, 3], dtype="Int64")
|
|
tm.assert_extension_array_equal(result, expected)
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"np_dtype, dtype",
|
|
[
|
|
("float32", "Float64"),
|
|
("int64", "Float64"),
|
|
("int64", "Int32"),
|
|
("float64", "Int64"),
|
|
("bool", "boolean"),
|
|
("float64", "string"),
|
|
("datetime64[ns]", "datetime64[us]"),
|
|
("timedelta64[ns]", "timedelta64[us]"),
|
|
pytest.param("int64", "int64[pyarrow]", marks=td.skip_if_no("pyarrow")),
|
|
pytest.param("float64", "float64[pyarrow]", marks=td.skip_if_no("pyarrow")),
|
|
pytest.param("bool", "bool[pyarrow]", marks=td.skip_if_no("pyarrow")),
|
|
pytest.param("float64", "string[pyarrow]", marks=td.skip_if_no("pyarrow")),
|
|
pytest.param(
|
|
"datetime64[ns]",
|
|
"timestamp[ns][pyarrow]",
|
|
marks=td.skip_if_no("pyarrow"),
|
|
),
|
|
pytest.param(
|
|
"timedelta64[ns]",
|
|
"duration[ns][pyarrow]",
|
|
marks=td.skip_if_no("pyarrow"),
|
|
),
|
|
],
|
|
)
|
|
def test_masked_array_explicit_dtype(np_dtype, dtype):
|
|
# GH#63879 - an explicitly passed dtype takes precedence over the dtype
|
|
# inferred from the masked array, and masked values become NA
|
|
ma_arr = ma.array([1, 2, 3], mask=[False, True, False], dtype=np_dtype)
|
|
result = pd.array(ma_arr, dtype=dtype)
|
|
expected = pd.array(ma_arr).astype(dtype)
|
|
tm.assert_extension_array_equal(result, expected)
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"data, expected",
|
|
[
|
|
(["a", "b", "c"], ["a", pd.NA, "c"]),
|
|
([b"abc", b"def", "café".encode()], ["abc", pd.NA, "café"]),
|
|
],
|
|
ids=["str", "bytes"],
|
|
)
|
|
def test_masked_array_string(data, expected):
|
|
# GH#63879 - str and bytes masked arrays both infer the string dtype (bytes
|
|
# are UTF-8 decoded), consistently with the no-missing-value case
|
|
result = pd.array(ma.array(data, mask=[False, True, False]))
|
|
expected = pd.array(expected, dtype="string")
|
|
tm.assert_extension_array_equal(result, expected)
|
|
|
|
|
|
def test_pd_array_structured_masked_array_raises():
|
|
# GH#63879 - structured MaskedArrays should raise (match Series behavior)
|
|
arr = np.array([(1, 2), (2, 3)], dtype="i8,i8")
|
|
ma_arr = np.ma.array(arr, mask=[(False, True), (False, True)])
|
|
msg = "Cannot construct an array from an ndarray with compound dtype"
|
|
with pytest.raises(ValueError, match=msg):
|
|
pd.array(ma_arr)
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"data, dtype, expected_data",
|
|
[
|
|
(
|
|
["1970-01-01T00:00:00.000000001"],
|
|
"datetime64[ns]",
|
|
["1970-01-01T00:00:00.000000001"],
|
|
),
|
|
(
|
|
[1],
|
|
"timedelta64[ns]",
|
|
["1 nanoseconds"],
|
|
),
|
|
],
|
|
)
|
|
def test_numpy_datetime_like_to_string(data, dtype, expected_data):
|
|
arr = np.array(data, dtype=dtype)
|
|
result = pd.array(arr, dtype="string")
|
|
expected = (
|
|
pd.StringDtype()
|
|
.construct_array_type()
|
|
._from_sequence(expected_data, dtype=pd.StringDtype())
|
|
)
|
|
|
|
tm.assert_equal(result, expected)
|