8000 BUG: DataFrame.append with timedelta64 by jbrockmendel · Pull Request #39574 · pandas-dev/pandas · GitHub
[go: up one dir, main page]

Skip to content

BUG: DataFrame.append with timedelta64 #39574

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 16 commits into from
Feb 12, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
check compatibility in JoinUnit.is_na
  • Loading branch information
jbrockmendel committed Feb 9, 2021
commit 1c63c05d4842dd71bcde19ffa221a532c6e7d3aa
3 changes: 2 additions & 1 deletion pandas/core/dtypes/concat.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,8 @@ def concat_compat(to_concat, axis: int = 0, ea_compat_axis: bool = False):
to_concat : array of arrays
axis : axis to provide concatenation
ea_compat_axis : bool, default False
For ExtensionArray compat, behave as if axis == 1
For ExtensionArray compat, behave as if axis == 1 when determining
whether to drop empty arrays.

Returns
-------
Expand Down
30 changes: 26 additions & 4 deletions pandas/core/internals/concat.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
is_sparse,
)
from pandas.core.dtypes.concat import concat_compat
from pandas.core.dtypes.missing import isna_all
from pandas.core.dtypes.missing import is_valid_nat_for_dtype, isna_all

import pandas.core.algorithms as algos
from pandas.core.arrays import DatetimeArray, ExtensionArray, TimedeltaArray
Expand Down Expand Up @@ -227,6 +227,24 @@ def dtype(self):
else:
return get_dtype(maybe_promote(self.block.dtype, self.block.fill_value)[0])

def is_valid_na_for(self, dtype: DtypeObj) -> bool:
"""
Check that we are all-NA of a type/dtype that is compatible with this dtype.
"""
if not self.is_na:
return False
if self.block is None:
return True

if self.dtype == object:
values = self.block.values
return all(
is_valid_nat_for_dtype(x, dtype) for x in values.ravel(order="K")
)
Copy link
Member
@jorisvandenbossche jorisvandenbossche Feb 10, 2021

Choose a reason for hiding this comment

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

This is not only required for object dtype, I think. Also float NaN is considered "all NaN" when it comes to ignoring the dtype in concatting dataframes (and other dtypes as well I think):

In [39]: pd.concat([pd.DataFrame({'a': [np.nan, np.nan]}), pd.DataFrame({'a': [pd.Timestamp("2012-01-01")]})])
Out[39]: 
           a
0        NaT
1        NaT
0 2012-01-01

Copy link
Member Author

Choose a reason for hiding this comment

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

the non-object case is handled below on L245-246. or do you have something else in mind?

Copy link
Member

Choose a reason for hiding this comment

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

Does my snippet above work with this PR?
(if so, then I don't fully understand why the changes to test_append_empty_frame_to_series_with_dateutil_tz are needed)

Copy link
Member Author

Choose a reason for hiding this comment

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

Does my snippet above work with this PR?

yes it does

(if so, then I don't fully understand why the changes to test_append_empty_frame_to_series_with_dateutil_tz are needed)

I think that's driven by something sketchy-looking in get_reindexed_values, will see if that can be addressed.

Copy link
Member Author

Choose a reason for hiding this comment

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

better?


na_value = self.block.fill_value
return is_valid_nat_for_dtype(na_value, dtype)

@cache_readonly
def is_na(self) -> bool:
if self.block is None:
Expand Down Expand Up @@ -257,7 +275,7 @@ def get_reindexed_values(self, empty_dtype: DtypeObj, upcasted_na) -> ArrayLike:
else:
fill_value = upcasted_na

if self.is_na:
if self.is_valid_na_for(empty_dtype):
blk_dtype = getattr(self.block, "dtype", None)

if blk_dtype == np.dtype(object):
Expand Down Expand Up @@ -418,8 +436,12 @@ def _get_empty_dtype(join_units: Sequence[JoinUnit]) -> DtypeObj:
return empty_dtype

has_none_blocks = any(unit.block is None for unit in join_units)
dtypes = [None if unit.block is None else unit.dtype for unit in join_units]
dtypes = [x for x in dtypes if x is not None]

dtypes = [
unit.dtype for unit in join_units if unit.block is not None and not unit.is_na
]
if not len(dtypes):
dtypes = [unit.dtype for unit in join_units if unit.block is not None]

dtype = find_common_type(dtypes)
if has_none_blocks:
Expand Down
6 changes: 3 additions & 3 deletions pandas/tests/frame/methods/test_append.py
57A7
Original file line number Diff line number Diff line change
Expand Up @@ -165,23 +165,23 @@ def test_append_dtypes(self):
df2 = DataFrame({"bar": np.nan}, index=range(1, 2))
result = df1.append(df2)
expected = DataFrame(
{"bar": Series([Timestamp("20130101"), np.nan], dtype="object")}
{"bar": Series([Timestamp("20130101"), np.nan], dtype="M8[ns]")}
)
tm.assert_frame_equal(result, expected)

df1 = DataFrame({"bar": Timestamp("20130101")}, index=range(1))
df2 = DataFrame({"bar": np.nan}, index=range(1, 2), dtype=object)
result = df1.append(df2)
expected = DataFrame(
{"bar": Series([Timestamp("20130101"), np.nan], dtype="object")}
{"bar": Series([Timestamp("20130101"), np.nan], dtype="M8[ns]")}
)
tm.assert_frame_equal(result, expected)

df1 = DataFrame({"bar": np.nan}, index=range(1))
df2 = DataFrame({"bar": Timestamp("20130101")}, index=range(1, 2))
result = df1.append(df2)
expected = DataFrame(
{"bar": Series([np.nan, Timestamp("20130101")], dtype="object")}
{"bar": Series([np.nan, Timestamp("20130101")], dtype="M8[ns]")}
)
tm.assert_frame_equal(result, expected)

Expand Down
3 changes: 1 addition & 2 deletions pandas/tests/indexing/test_partial.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,8 +160,7 @@ def test_partial_setting_mixed_dtype(self):
df = DataFrame(columns=["A", "B"])
df.loc[0] = Series(1, index=["B"])

# TODO: having this be float64 would not be unreasonable
exp = DataFrame([[np.nan, 1]], columns=["A", "B"], index=[0], dtype="object")
exp = DataFrame([[np.nan, 1]], columns=["A", "B"], index=[0], dtype="float64")
tm.assert_frame_equal(df, exp)

# list-like must conform
Expand Down
1 change: 0 additions & 1 deletion pandas/tests/reshape/merge/test_merge.py
Original file line number Diff line number Diff line change
Expand Up @@ -670,7 +670,6 @@ def test_join_append_timedeltas(self):
"t": [timedelta(0, 22500), timedelta(0, 22500)],
}
)
expected = expected.astype(object)
tm.assert_frame_equal(result, expected)

td = np.timedelta64(300000000)
Expand Down
0