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

Conversation

wxing11
Copy link
Contributor

@wxing11 wxing11 commented Oct 30, 2022

@@ -8195,6 +8195,10 @@ def update(
for col in self.columns:
this = self[col]._values
that = other[col]._values

if all(isna(that)):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

From the original issue, it suggests that this may be an issue in the reindex_like operations being incompatible with something, so I don't think a patched-over check like this is appropriate

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi! Thanks for reviewing!

This was my assessment of it in the original issue: #16713 (comment)

Based on that, I think the issue in reindex_like is just that when it creates columns that aren't in the pre-reindex dataframe that they aren't datetime/datetime compatible by default. Is that the part I should be looking to change instead?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is that the part I should be looking to change instead?

Ideally yes, or possibly when the masks are compared.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will look into this more, thanks for the guidance!


for col in self.columns:
shared_cols = self.columns.intersection(other.columns)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@MarcoGorelli I know this solution kinda side-steps the original issue of null-matching (and reindex introducing an entire NA-column that doesn't need updating I think), but happy to have your thoughts on this solution.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is fine

Something that comes to mind is that it'll still error if other contains a column all of nan, e.g.:

In [1]: df1 = pd.DataFrame({'a': [NaT]})

In [2]: df2 = pd.DataFrame({'a': [np.nan]})

In [3]: df1.update(df2, overwrite=False)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In [3], line 1
----> 1 df1.update(df2, overwrite=False)

File ~/pandas-dev/pandas/core/frame.py:8096, in DataFrame.update(self, other, join, overwrite, filter_func, errors)
   8093 if mask.all():
   8094     continue
-> 8096 self.loc[:, col] = expressions.where(mask, this, that)

File ~/pandas-dev/pandas/core/computation/expressions.py:258, in where(cond, a, b, use_numexpr)
    246 """
    247 Evaluate the where condition cond on a and b.
    248 
   (...)
    255     Whether to try to use numexpr.
    256 """
    257 assert _where is not None
--> 258 return _where(cond, a, b) if use_numexpr else _where_standard(cond, a, b)

File ~/pandas-dev/pandas/core/computation/expressions.py:188, in _where_numexpr(cond, a, b)
    181     result = ne.evaluate(
    182         "where(cond_value, a_value, b_value)",
    183         local_dict={"cond_value": cond, "a_value": a, "b_value": b},
    184         casting="safe",
    185     )
    187 if result is None:
--> 188     result = _where_standard(cond, a, b)
    190 return result

File ~/pandas-dev/pandas/core/computation/expressions.py:172, in _where_standard(cond, a, b)
    170 def _where_standard(cond, a, b):
    171     # Caller is responsible for extracting ndarray if necessary
--> 172     return np.where(cond, a, b)

File <__array_function__ internals>:180, in where(*args, **kwargs)

TypeError: The DType <class 'numpy.dtype[datetime64]'> could not be promoted by <class 'numpy.dtype[float64]'>. This means that no common DType exists for the given inputs. For example they cannot be stored in a single array unless the dtype is `object`. The full list of DTypes is: (<class 'numpy.dtype[datetime64]'>, <class 'numpy.dtype[float64]'>)

but arguably that's desirable behaviour - you wouldn't want to update with a column of an incompatible dtype, regardless of whether its values were all missing or not.

And value-dependent behaviour wouldn't be great, so I like this solution more than the originally-suggested "if all nan then skip"

Copy link
Member

@MarcoGorelli MarcoGorelli left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The solution looks fine to me, I like this more than the originally-suggested one

This'll need a whatsnew note too


for col in self.columns:
shared_cols = self.columns.intersection(other.columns)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is fine

Something that comes to mind is that it'll still error if other contains a column all of nan, e.g.:

In [1]: df1 = pd.DataFrame({'a': [NaT]})

In [2]: df2 = pd.DataFrame({'a': [np.nan]})

In [3]: df1.update(df2, overwrite=False)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In [3], line 1
----> 1 df1.update(df2, overwrite=False)

File ~/pandas-dev/pandas/core/frame.py:8096, in DataFrame.update(self, other, join, overwrite, filter_func, errors)
   8093 if mask.all():
   8094     continue
-> 8096 self.loc[:, col] = expressions.where(mask, this, that)

File ~/pandas-dev/pandas/core/computation/expressions.py:258, in where(cond, a, b, use_numexpr)
    246 """
    247 Evaluate the where condition cond on a and b.
    248 
   (...)
    255     Whether to try to use numexpr.
    256 """
    257 assert _where is not None
--> 258 return _where(cond, a, b) if use_numexpr else _where_standard(cond, a, b)

File ~/pandas-dev/pandas/core/computation/expressions.py:188, in _where_numexpr(cond, a, b)
    181     result = ne.evaluate(
    182         "where(cond_value, a_value, b_value)",
    183         local_dict={"cond_value": cond, "a_value": a, "b_value": b},
    184         casting="safe",
    185     )
    187 if result is None:
--> 188     result = _where_standard(cond, a, b)
    190 return result

File ~/pandas-dev/pandas/core/computation/expressions.py:172, in _where_standard(cond, a, b)
    170 def _where_standard(cond, a, b):
    171     # Caller is responsible for extracting ndarray if necessary
--> 172     return np.where(cond, a, b)

File <__array_function__ internals>:180, in where(*args, **kwargs)

TypeError: The DType <class 'numpy.dtype[datetime64]'> could not be promoted by <class 'numpy.dtype[float64]'>. This means that no common DType exists for the given inputs. For example they cannot be stored in a single array unless the dtype is `object`. The full list of DTypes is: (<class 'numpy.dtype[datetime64]'>, <class 'numpy.dtype[float64]'>)

but arguably that's desirable behaviour - you wouldn't want to update with a column of an incompatible dtype, regardless of whether its values were all missing or not.

And value-dependent behaviour wouldn't be great, so I like this solution more than the originally-suggested "if all nan then skip"

for col in self.columns:
shared_cols = self.columns.intersection(other.columns)

for col in shared_cols:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

let's keep it on one line

        for col in self.columns.intersection(other.columns):

@@ -8190,11 +8190,15 @@ def update(
if not isinstance(other, DataFrame):
other = DataFrame(other)

other = other.reindex_like(self)
# reindex rows, non-matching columns get skipped
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not sure we need this comment

Comment on lines 174 to 177
"B": [
pd.NaT,
pd.to_datetime("2016-01-01"),
],
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we keep this on a single line?

}
)
df2 = DataFrame({"A": [2, 3]})

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

let's remove all these newlines in the tests


tm.assert_frame_equal(df, expected)

def test_update_dt_column_with_NaT_create_row(self):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not really sure what this test adds, I'd suggest to either:

  • parametrize over the first test
  • just remove this one

@wxing11
Copy link
Contributor Author

wxing11 commented Nov 9, 2022

@MarcoGorelli Made changes for the comments you left and added to the whatsnew!

@MarcoGorelli MarcoGorelli self-requested a review November 9, 2022 09:11
Copy link
Member

@MarcoGorelli MarcoGorelli left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The change looks good to me (@mroeschke any further comments?), I just have a small comment on the whatsnew note

@@ -376,6 +376,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` raising ``TypeError`` when column has NaT values (:issue:`16713`)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we clarify please - if I understand correctly, it was only raising a TypeError if the column had NaT values and it wasn't present in the other DataFrame and you were using overwrite=False

Also, if you write NaT, make sure to put double ticks around it, like this

``NaT``

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated the message, let me know if the new one works!

Copy link
Member

@mroeschke mroeschke left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changes look fine to me. Merge when all ready @MarcoGorelli

Copy link
Member

@MarcoGorelli MarcoGorelli left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Making a minor update to docs, hope it's OK, but rest looks good, thanks @wxing11 !

@MarcoGorelli MarcoGorelli added this to the 2.0 milestone Nov 15, 2022
@MarcoGorelli MarcoGorelli merged commit 12ff4f4 into pandas-dev:main Nov 15, 2022
MarcoGorelli added a commit to MarcoGorelli/pandas that referenced this pull request Nov 18, 2022
* Fixes DataFrame.update crashes when NaT present. GH16713

* Formatting

* No longer reindexing columns, skipping non-matching columns

* switching to using set intersection to find shared columns

* switching to using index intersection

* Removing unnecessary variable creation

* Formatting and removing test

* Adding to whatsnew

* updating whatsnew message

* Update doc/source/whatsnew/v2.0.0.rst

Co-authored-by: Marco Edward Gorelli <[email protected]>
mliu08 pushed a commit to mliu08/pandas that referenced this pull request Nov 27, 2022
* Fixes DataFrame.update crashes when NaT present. GH16713

* Formatting

* No longer reindexing columns, skipping non-matching columns

* switching to using set intersection to find shared columns

* switching to using index intersection

* Removing unnecessary variable creation

* Formatting and removing test

* Adding to whatsnew

* updating whatsnew message

* Update doc/source/whatsnew/v2.0.0.rst

Co-authored-by: Marco Edward Gorelli <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
DataFrame DataFrame data structure
Projects
None yet
Development

Successfully merging this pull request may close these issues.

DataFrame.update crashes with overwrite=False when NaT present
3 participants