Skip to content

Commit 6e1e1e4

Browse files
DylanDmitrijreback
authored andcommitted
fix: scalar timestamp assignment (#19843) (#19973)
1 parent 5076ebe commit 6e1e1e4

File tree

3 files changed

+16
-2
lines changed

3 files changed

+16
-2
lines changed

doc/source/whatsnew/v0.24.0.txt

+1
Original file line numberDiff line numberDiff line change
@@ -560,6 +560,7 @@ Timezones
560560
- Bug in :class:`DatetimeIndex` where constructing with an integer and tz would not localize correctly (:issue:`12619`)
561561
- Fixed bug where :meth:`DataFrame.describe` and :meth:`Series.describe` on tz-aware datetimes did not show `first` and `last` result (:issue:`21328`)
562562
- Bug in :class:`DatetimeIndex` comparisons failing to raise ``TypeError`` when comparing timezone-aware ``DatetimeIndex`` against ``np.datetime64`` (:issue:`22074`)
563+
- Bug in ``DataFrame`` assignment with a timezone-aware scalar (:issue:`19843`)
563564

564565
Offsets
565566
^^^^^^^

pandas/core/frame.py

+7-2
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
maybe_upcast,
2828
cast_scalar_to_array,
2929
construct_1d_arraylike_from_scalar,
30+
infer_dtype_from_scalar,
3031
maybe_cast_to_datetime,
3132
maybe_infer_to_datetimelike,
3233
maybe_convert_platform,
@@ -3507,9 +3508,13 @@ def reindexer(value):
35073508
value = maybe_infer_to_datetimelike(value)
35083509

35093510
else:
3510-
# upcast the scalar
3511+
# cast ignores pandas dtypes. so save the dtype first
3512+
infer_dtype, _ = infer_dtype_from_scalar(
3513+
value, pandas_dtype=True)
3514+
3515+
# upcast
35113516
value = cast_scalar_to_array(len(self.index), value)
3512-
value = maybe_cast_to_datetime(value, value.dtype)
3517+
value = maybe_cast_to_datetime(value, infer_dtype)
35133518

35143519
# return internal types directly
35153520
if is_extension_type(value) or is_extension_array_dtype(value):

pandas/tests/frame/test_indexing.py

+8
Original file line numberDiff line numberDiff line change
@@ -3135,6 +3135,14 @@ def test_transpose(self):
31353135
expected.index = ['A', 'B']
31363136
assert_frame_equal(result, expected)
31373137

3138+
def test_scalar_assignment(self):
3139+
# issue #19843
3140+
df = pd.DataFrame(index=(0, 1, 2))
3141+
df['now'] = pd.Timestamp('20130101', tz='UTC')
3142+
expected = pd.DataFrame(
3143+
{'now': pd.Timestamp('20130101', tz='UTC')}, index=[0, 1, 2])
3144+
tm.assert_frame_equal(df, expected)
3145+
31383146

31393147
class TestDataFrameIndexingUInt64(TestData):
31403148

0 commit comments

Comments
 (0)