From 6e1e1e40f7e474886f46b88edfd4c5bc22a35b14 Mon Sep 17 00:00:00 2001 From: Dylan Dmitri Gray Date: Thu, 2 Aug 2018 10:27:22 -0700 Subject: [PATCH] fix: scalar timestamp assignment (#19843) (#19973) --- doc/source/whatsnew/v0.24.0.txt | 1 + pandas/core/frame.py | 9 +++++++-- pandas/tests/frame/test_indexing.py | 8 ++++++++ 3 files changed, 16 insertions(+), 2 deletions(-) diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index b7692f51c4ddf..5c15c7b6a742f 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -560,6 +560,7 @@ Timezones - Bug in :class:`DatetimeIndex` where constructing with an integer and tz would not localize correctly (:issue:`12619`) - Fixed bug where :meth:`DataFrame.describe` and :meth:`Series.describe` on tz-aware datetimes did not show `first` and `last` result (:issue:`21328`) - Bug in :class:`DatetimeIndex` comparisons failing to raise ``TypeError`` when comparing timezone-aware ``DatetimeIndex`` against ``np.datetime64`` (:issue:`22074`) +- Bug in ``DataFrame`` assignment with a timezone-aware scalar (:issue:`19843`) Offsets ^^^^^^^ diff --git a/pandas/core/frame.py b/pandas/core/frame.py index bbe84110fd019..cb251d4648925 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -27,6 +27,7 @@ maybe_upcast, cast_scalar_to_array, construct_1d_arraylike_from_scalar, + infer_dtype_from_scalar, maybe_cast_to_datetime, maybe_infer_to_datetimelike, maybe_convert_platform, @@ -3507,9 +3508,13 @@ def reindexer(value): value = maybe_infer_to_datetimelike(value) else: - # upcast the scalar + # cast ignores pandas dtypes. so save the dtype first + infer_dtype, _ = infer_dtype_from_scalar( + value, pandas_dtype=True) + + # upcast value = cast_scalar_to_array(len(self.index), value) - value = maybe_cast_to_datetime(value, value.dtype) + value = maybe_cast_to_datetime(value, infer_dtype) # return internal types directly if is_extension_type(value) or is_extension_array_dtype(value): diff --git a/pandas/tests/frame/test_indexing.py b/pandas/tests/frame/test_indexing.py index 5f229aca5c25b..d885df76967b8 100644 --- a/pandas/tests/frame/test_indexing.py +++ b/pandas/tests/frame/test_indexing.py @@ -3135,6 +3135,14 @@ def test_transpose(self): expected.index = ['A', 'B'] assert_frame_equal(result, expected) + def test_scalar_assignment(self): + # issue #19843 + df = pd.DataFrame(index=(0, 1, 2)) + df['now'] = pd.Timestamp('20130101', tz='UTC') + expected = pd.DataFrame( + {'now': pd.Timestamp('20130101', tz='UTC')}, index=[0, 1, 2]) + tm.assert_frame_equal(df, expected) + class TestDataFrameIndexingUInt64(TestData):