Skip to content

Commit

Permalink
ENH: support 2D in DatetimeArray._from_sequence (#38021)
Browse files Browse the repository at this point in the history
  • Loading branch information
jbrockmendel authored Dec 17, 2020
1 parent bffc7ad commit baeacad
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
8 changes: 6 additions & 2 deletions pandas/core/arrays/datetimes.py
Original file line number Diff line number Diff line change
Expand Up @@ -2071,20 +2071,24 @@ def objects_to_datetime64ns(
# if str-dtype, convert
data = np.array(data, copy=False, dtype=np.object_)

flags = data.flags
order = "F" if flags.f_contiguous else "C"
try:
result, tz_parsed = tslib.array_to_datetime(
data,
data.ravel("K"),
errors=errors,
utc=utc,
dayfirst=dayfirst,
yearfirst=yearfirst,
require_iso8601=require_iso8601,
)
result = result.reshape(data.shape, order=order)
except ValueError as e:
try:
values, tz_parsed = conversion.datetime_to_datetime64(data)
values, tz_parsed = conversion.datetime_to_datetime64(data.ravel("K"))
# If tzaware, these values represent unix timestamps, so we
# return them as i8 to distinguish from wall times
values = values.reshape(data.shape, order=order)
return values.view("i8"), tz_parsed
except (ValueError, TypeError):
raise e
Expand Down
18 changes: 18 additions & 0 deletions pandas/tests/arrays/test_datetimes.py
Original file line number Diff line number Diff line change
Expand Up @@ -465,6 +465,24 @@ def test_tz_dtype_matches(self):
result, _, _ = sequence_to_dt64ns(arr, dtype=DatetimeTZDtype(tz="US/Central"))
tm.assert_numpy_array_equal(arr._data, result)

@pytest.mark.parametrize("order", ["F", "C"])
def test_2d(self, order):
dti = pd.date_range("2016-01-01", periods=6, tz="US/Pacific")
arr = np.array(dti, dtype=object).reshape(3, 2)
if order == "F":
arr = arr.T

res = sequence_to_dt64ns(arr)
expected = sequence_to_dt64ns(arr.ravel())

tm.assert_numpy_array_equal(res[0].ravel(), expected[0])
assert res[1] == expected[1]
assert res[2] == expected[2]

res = DatetimeArray._from_sequence(arr)
expected = DatetimeArray._from_sequence(arr.ravel()).reshape(arr.shape)
tm.assert_datetime_array_equal(res, expected)


class TestReductions:
@pytest.fixture
Expand Down

0 comments on commit baeacad

Please sign in to comment.