Skip to content

BUG: Series.plot.bar() raises TypeError on timedelta dtype #39320

Open
@darkdragon-001

Description

@darkdragon-001
  • 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 pandas as pd
df = pd.DataFrame({'ts1': pd.to_datetime([0, 1, 2, 3], unit='s'), 'ts2': pd.to_datetime([1, 1, 5, 4], unit='s')})
diff = df['ts2']-df['ts1']
diff.plot.bar()

Problem description

Pandas uses fillna() to produce valid data points. Unforunately, the data type timedelta64[ns] doesn't support setting to integer 0.

Output:

TypeError                                 Traceback (most recent call last)
 in 
      2 df = pd.DataFrame({'ts1': pd.to_datetime([0, 1, 2, 3], unit='s'), 'ts2': pd.to_datetime([1, 1, 5, 4], unit='s')})
      3 diff = df['ts2']-df['ts1']
----> 4 diff.plot.bar()

~/.local/lib/python3.9/site-packages/pandas/plotting/_core.py in bar(self, x, y, **kwargs)
1111 other axis represents a measured value.
1112 """
-> 1113 return self(kind="bar", x=x, y=y, **kwargs)
1114
1115 @Appender(

~/.local/lib/python3.9/site-packages/pandas/plotting/_core.py in call(self, *args, **kwargs)
953 data.columns = label_name
954
--> 955 return plot_backend.plot(data, kind=kind, **kwargs)
956
957 call.doc = doc

~/.local/lib/python3.9/site-packages/pandas/plotting/_matplotlib/init.py in plot(data, kind, **kwargs)
59 kwargs["ax"] = getattr(ax, "left_ax", ax)
60 plot_obj = PLOT_CLASSES[kind](data, **kwargs)
---> 61 plot_obj.generate()
62 plot_obj.draw()
63 return plot_obj.result

~/.local/lib/python3.9/site-packages/pandas/plotting/_matplotlib/core.py in generate(self)
278 self._compute_plot_data()
279 self._setup_subplots()
--> 280 self._make_plot()
281 self._add_table()
282 self._make_legend()

~/.local/lib/python3.9/site-packages/pandas/plotting/_matplotlib/core.py in _make_plot(self)
1419 K = self.nseries
1420
-> 1421 for i, (label, y) in enumerate(self._iter_data(fillna=0)):
1422 ax = self._get_ax(i)
1423 kwds = self.kwds.copy()

~/.local/lib/python3.9/site-packages/pandas/plotting/_matplotlib/core.py in _iter_data(self, data, keep_index, fillna)
256 data = self.data
257 if fillna is not None:
--> 258 data = data.fillna(fillna)
259
260 for col, values in data.items():

~/.local/lib/python3.9/site-packages/pandas/core/frame.py in fillna(self, value, method, axis, inplace, limit, downcast)
4457 downcast=None,
4458 ) -> Optional[DataFrame]:
-> 4459 return super().fillna(
4460 value=value,
4461 method=method,

~/.local/lib/python3.9/site-packages/pandas/core/generic.py in fillna(self, value, method, axis, inplace, limit, downcast)
6424
6425 elif not is_list_like(value):
-> 6426 new_data = self._mgr.fillna(
6427 value=value, limit=limit, inplace=inplace, downcast=downcast
6428 )

~/.local/lib/python3.9/site-packages/pandas/core/internals/managers.py in fillna(self, value, limit, inplace, downcast)
619
620 def fillna(self, value, limit, inplace: bool, downcast) -> "BlockManager":
--> 621 return self.apply(
622 "fillna", value=value, limit=limit, inplace=inplace, downcast=downcast
623 )

~/.local/lib/python3.9/site-packages/pandas/core/internals/managers.py in apply(self, f, align_keys, ignore_failures, **kwargs)
425 applied = b.apply(f, **kwargs)
426 else:
--> 427 applied = getattr(b, f)(**kwargs)
428 except (TypeError, NotImplementedError):
429 if not ignore_failures:

~/.local/lib/python3.9/site-packages/pandas/core/internals/blocks.py in fillna(self, value, **kwargs)
2478 if is_integer(value):
2479 # Deprecation GH#24694, GH#19233
-> 2480 raise TypeError(
2481 "Passing integers to fillna for timedelta64[ns] dtype is no "
2482 "longer supported. To obtain the old behavior, pass "

TypeError: Passing integers to fillna for timedelta64[ns] dtype is no longer supported. To obtain the old behavior, pass pd.Timedelta(seconds=n) instead.

Expected Output

Bar plot.

Output of pd.show_versions()

INSTALLED VERSIONS
------------------
commit           : 9d598a5e1eee26df95b3910e3f2934890d062caa
python           : 3.9.1.final.0
python-bits      : 64
OS               : Linux
OS-release       : 5.10.8-200.fc33.x86_64
Version          : #1 SMP Sun Jan 17 19:53:01 UTC 2021
machine          : x86_64
processor        : x86_64
byteorder        : little
LC_ALL           : en_US.UTF-8
LANG             : en_US.UTF-8
LOCALE           : en_US.UTF-8

pandas : 1.2.1
numpy : 1.19.5
pytz : 2020.5
dateutil : 2.8.1
pip : 20.1.1
setuptools : 51.1.0
Cython : None
pytest : None
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : 4.6.2
html5lib : 1.1
pymysql : None
psycopg2 : None
jinja2 : 2.11.2
IPython : 7.19.0
pandas_datareader: None
bs4 : 4.9.3
bottleneck : None
fsspec : None
fastparquet : None
gcsfs : None
matplotlib : 3.3.3
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : None
pyxlsb : None
s3fs : None
scipy : None
sqlalchemy : None
tables : None
tabulate : 0.8.7
xarray : None
xlrd : None
xlwt : None
numba : None

Metadata

Metadata

Labels

BugMissing-datanp.nan, pd.NaT, pd.NA, dropna, isnull, interpolateRegressionFunctionality that used to work in a prior pandas versionTimedeltaTimedelta data typeVisualizationplotting

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions