diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index 3cff1522274ef..9fc087dce752f 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -559,6 +559,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 ebd35cb1a6a1a..b7894881feb40 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):