Skip to content

BUG: Fixing DataFrame.Update crashes when NaT present #49395

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 11 commits into from
Nov 15, 2022
1 change: 1 addition & 0 deletions doc/source/whatsnew/v2.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -662,6 +662,7 @@ Missing
- Bug in :meth:`Index.equals` raising ``TypeError`` when :class:`Index` consists of tuples that contain ``NA`` (:issue:`48446`)
- Bug in :meth:`Series.map` caused incorrect result when data has NaNs and defaultdict mapping was used (:issue:`48813`)
- Bug in :class:`NA` raising a ``TypeError`` instead of return :class:`NA` when performing a binary operation with a ``bytes`` object (:issue:`49108`)
- Bug in :meth:`DataFrame.update` with ``overwrite=False`` raising ``TypeError`` when ``self`` has column with ``NaT`` values and column not present in ``other`` (:issue:`16713`)

MultiIndex
^^^^^^^^^^
Expand Down
5 changes: 3 additions & 2 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -8056,11 +8056,12 @@ def update(
if not isinstance(other, DataFrame):
other = DataFrame(other)

other = other.reindex_like(self)
other = other.reindex(self.index)

for col in self.columns:
for col in self.columns.intersection(other.columns):
this = self[col]._values
that = other[col]._values

if filter_func is not None:
with np.errstate(all="ignore"):
mask = ~filter_func(this) | isna(that)
Expand Down
10 changes: 10 additions & 0 deletions pandas/tests/frame/methods/test_update.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,3 +166,13 @@ def test_update_modify_view(self, using_copy_on_write):
tm.assert_frame_equal(result_view, df2_orig)
else:
tm.assert_frame_equal(result_view, expected)

def test_update_dt_column_with_NaT_create_column(self):
# GH#16713
df = DataFrame({"A": [1, None], "B": [pd.NaT, pd.to_datetime("2016-01-01")]})
df2 = DataFrame({"A": [2, 3]})
df.update(df2, overwrite=False)
expected = DataFrame(
{"A": [1.0, 3.0], "B": [pd.NaT, pd.to_datetime("2016-01-01")]}
)
tm.assert_frame_equal(df, expected)