Skip to content

BUG: mask method fails on Timedelta series with numpy 1.20 #39548

Closed
@jeffzi

Description

@jeffzi
  • I have checked that this issue has not already been reported.

  • I have confirmed this bug exists on the latest version of pandas.

  • (optional) I have confirmed this bug exists on the master branch of pandas.


Code Sample, a copy-pastable example

import numpy as np
import pandas as pd

td = pd.Series([pd.Timedelta(days=i) for i in range(3)])

try:
    # same as td.mask([False, False, True])
    td.where([False, False, True], np.nan)
except TypeError as err:
    print(err)
#> The DTypes <class 'numpy.dtype[float16]'> and <class 'numpy.dtype[timedelta64]'> do not have a common DType. For example they cannot be stored in a single array unless the dtype is `object`.

# gives same result as above on numpy < 1.20
print(td.where([False, False, True], pd.NaT))
#> 0      NaT
#> 1      NaT
#> 2   2 days
#> dtype: timedelta64[ns]

# also ok
print(td.where([False, False, True], 10.0))
#> 0               10.0
#> 1               10.0
#> 2    2 days 00:00:00
#> dtype: object

td.where([False, False, True], np.nan, inplace=True) # ok
print(td)
#> 0      NaT
#> 1      NaT
#> 2   2 days
#> dtype: timedelta64[ns]

Created on 2021-02-02 by the reprexpy package

Problem description

With numpy 1.20.0, mask on a Series of dtype timedelta64 raises a TypeError. The code above shows that the issue comes from the internals of where and happens only when a np.nan is passed as replacement value.

I noticed that inplace=True avoids the issue.

Expected Output

td.mask(...) should return the same as where(..., pd.NaT)

Output of pd.show_versions()

INSTALLED VERSIONS

commit : 9d598a5
python : 3.8.6.final.0
python-bits : 64
OS : Linux
OS-release : 5.10.7-3-MANJARO
Version : #1 SMP PREEMPT Fri Jan 15 21:11:34 UTC 2021
machine : x86_64
processor :
byteorder : little
LC_ALL : None
LANG : en_US.UTF-8
LOCALE : en_US.UTF-8

pandas : 1.2.1
numpy : 1.20.0
pytz : 2020.5
dateutil : 2.8.1
pip : 20.2.1
setuptools : 49.2.1
Cython : None
pytest : 6.2.2
hypothesis : 6.1.1
sphinx : 3.4.3
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : 2.11.3
IPython : 7.20.0
pandas_datareader: None
bs4 : None
bottleneck : None
fsspec : None
fastparquet : None
gcsfs : None
matplotlib : 3.3.4
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : None
pyxlsb : None
s3fs : None
scipy : 1.6.0
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
xlwt : None
numba : None

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions