Skip to content

BUG: timedelta as value to plot barplot raises error #48103

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

Closed
2 of 3 tasks
auderson opened this issue Aug 16, 2022 · 3 comments
Closed
2 of 3 tasks

BUG: timedelta as value to plot barplot raises error #48103

auderson opened this issue Aug 16, 2022 · 3 comments
Labels
Bug Needs Triage Issue that has not been reviewed by a pandas team member

Comments

@auderson
Copy link
Contributor

Pandas version checks

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

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

  • I have confirmed this bug exists on the main branch of pandas.

Reproducible Example

import pandas as pd

values = pd.array(["13min 54s", "3.74s", "462ms"], dtype="timedelta64[ns]")
pd.Series(values, index=["a", "b", "c"]).plot.bar()

Issue Description

the above code will produce following error:

File ~/miniconda3/envs/py3.10/lib/python3.10/site-packages/pandas/plotting/_core.py:1131, in PlotAccessor.bar(self, x, y, **kwargs)
   1043 @Appender(
   1044     """
   1045     See Also
   (...)
   1120 @Appender(_bar_or_line_doc)
   1121 def bar(self, x=None, y=None, **kwargs):
   1122     """
   1123     Vertical bar plot.
   1124 
   (...)
   1129     other axis represents a measured value.
   1130     """
-> 1131     return self(kind="bar", x=x, y=y, **kwargs)

File ~/miniconda3/envs/py3.10/lib/python3.10/site-packages/pandas/plotting/_core.py:972, in PlotAccessor.__call__(self, *args, **kwargs)
    969             label_name = label_kw or data.columns
    970             data.columns = label_name
--> 972 return plot_backend.plot(data, kind=kind, **kwargs)

File ~/miniconda3/envs/py3.10/lib/python3.10/site-packages/pandas/plotting/_matplotlib/__init__.py:71, in plot(data, kind, **kwargs)
     69         kwargs["ax"] = getattr(ax, "left_ax", ax)
     70 plot_obj = PLOT_CLASSES[kind](data, **kwargs)
---> 71 plot_obj.generate()
     72 plot_obj.draw()
     73 return plot_obj.result

File ~/miniconda3/envs/py3.10/lib/python3.10/site-packages/pandas/plotting/_matplotlib/core.py:329, in MPLPlot.generate(self)
    327 self._compute_plot_data()
    328 self._setup_subplots()
--> 329 self._make_plot()
    330 self._add_table()
    331 self._make_legend()

File ~/miniconda3/envs/py3.10/lib/python3.10/site-packages/pandas/plotting/_matplotlib/core.py:1503, in BarPlot._make_plot(self)
   1500 pos_prior = neg_prior = np.zeros(len(self.data))
   1501 K = self.nseries
-> 1503 for i, (label, y) in enumerate(self._iter_data(fillna=0)):
   1504     ax = self._get_ax(i)
   1505     kwds = self.kwds.copy()

File ~/miniconda3/envs/py3.10/lib/python3.10/site-packages/pandas/plotting/_matplotlib/core.py:300, in MPLPlot._iter_data(self, data, keep_index, fillna)
    298     data = self.data
    299 if fillna is not None:
--> 300     data = data.fillna(fillna)
    302 for col, values in data.items():
    303     if keep_index is True:

File ~/miniconda3/envs/py3.10/lib/python3.10/site-packages/pandas/util/_decorators.py:311, in deprecate_nonkeyword_arguments.<locals>.decorate.<locals>.wrapper(*args, **kwargs)
    305 if len(args) > num_allow_args:
    306     warnings.warn(
    307         msg.format(arguments=arguments),
    308         FutureWarning,
    309         stacklevel=stacklevel,
    310     )
--> 311 return func(*args, **kwargs)

File ~/miniconda3/envs/py3.10/lib/python3.10/site-packages/pandas/core/frame.py:5220, in DataFrame.fillna(self, value, method, axis, inplace, limit, downcast)
   5209 @deprecate_nonkeyword_arguments(version=None, allowed_args=["self", "value"])
   5210 @doc(NDFrame.fillna, **_shared_doc_kwargs)
   5211 def fillna(
   (...)
   5218     downcast=None,
   5219 ) -> DataFrame | None:
-> 5220     return super().fillna(
   5221         value=value,
   5222         method=method,
   5223         axis=axis,
   5224         inplace=inplace,
   5225         limit=limit,
   5226         downcast=downcast,
   5227     )

File ~/miniconda3/envs/py3.10/lib/python3.10/site-packages/pandas/core/generic.py:6498, in NDFrame.fillna(self, value, method, axis, inplace, limit, downcast)
   6495         new_data = result
   6496     else:
-> 6498         new_data = self._mgr.fillna(
   6499             value=value, limit=limit, inplace=inplace, downcast=downcast
   6500         )
   6501 elif isinstance(value, ABCDataFrame) and self.ndim == 2:
   6503     new_data = self.where(self.notna(), value)._mgr

File ~/miniconda3/envs/py3.10/lib/python3.10/site-packages/pandas/core/internals/managers.py:414, in BaseBlockManager.fillna(self, value, limit, inplace, downcast)
    413 def fillna(self: T, value, limit, inplace: bool, downcast) -> T:
--> 414     return self.apply(
    415         "fillna", value=value, limit=limit, inplace=inplace, downcast=downcast
    416     )

File ~/miniconda3/envs/py3.10/lib/python3.10/site-packages/pandas/core/internals/managers.py:304, in BaseBlockManager.apply(self, f, align_keys, ignore_failures, **kwargs)
    302         applied = b.apply(f, **kwargs)
    303     else:
--> 304         applied = getattr(b, f)(**kwargs)
    305 except (TypeError, NotImplementedError):
    306     if not ignore_failures:

File ~/miniconda3/envs/py3.10/lib/python3.10/site-packages/pandas/core/internals/blocks.py:1855, in NDArrayBackedExtensionBlock.fillna(self, value, limit, inplace, downcast)
   1847 if not self._can_hold_element(value) and self.dtype.kind != "m":
   1848     # We support filling a DatetimeTZ with a `value` whose timezone
   1849     #  is different by coercing to object.
   1850     # TODO: don't special-case td64
   1851     return self.coerce_to_target_dtype(value).fillna(
   1852         value, limit, inplace, downcast
   1853     )
-> 1855 new_values = self.values.fillna(value=value, limit=limit)
   1856 return [self.make_block_same_class(values=new_values)]

File ~/miniconda3/envs/py3.10/lib/python3.10/site-packages/pandas/core/arrays/_mixins.py:328, in NDArrayBackedExtensionArray.fillna(self, value, method, limit)
    325 else:
    326     # We validate the fill_value even if there is nothing to fill
    327     if value is not None:
--> 328         self._validate_setitem_value(value)
    330     new_values = self.copy()
    331 return new_values

File ~/miniconda3/envs/py3.10/lib/python3.10/site-packages/pandas/core/arrays/datetimelike.py:743, in DatetimeLikeArrayMixin._validate_setitem_value(self, value)
    741     value = self._validate_listlike(value)
    742 else:
--> 743     return self._validate_scalar(value, allow_listlike=True)
    745 return self._unbox(value, setitem=True)

File ~/miniconda3/envs/py3.10/lib/python3.10/site-packages/pandas/core/arrays/datetimelike.py:644, in DatetimeLikeArrayMixin._validate_scalar(self, value, allow_listlike, setitem, unbox)
    642 else:
    643     msg = self._validation_error_message(value, allow_listlike)
--> 644     raise TypeError(msg)
    646 if not unbox:
    647     # NB: In general NDArrayBackedExtensionArray will unbox here;
    648     #  this option exists to prevent a performance hit in
    649     #  TimedeltaIndex.get_loc
    650     return value

TypeError: value should be a 'Timedelta', 'NaT', or array of those. Got 'int' instead.

Expected Behavior

.

Installed Versions

/home/auderson/miniconda3/envs/py3.10/lib/python3.10/site-packages/_distutils_hack/init.py:33: UserWarning: Setuptools is replacing distutils.
warnings.warn("Setuptools is replacing distutils.")

INSTALLED VERSIONS

commit : e8093ba
python : 3.10.4.final.0
python-bits : 64
OS : Linux
OS-release : 5.8.0-63-generic
Version : #71-Ubuntu SMP Tue Jul 13 15:59:12 UTC 2021
machine : x86_64
processor : x86_64
byteorder : little
LC_ALL : None
LANG : en_US.UTF-8
LOCALE : en_US.UTF-8

pandas : 1.4.3
numpy : 1.21.6
pytz : 2022.1
dateutil : 2.8.2
setuptools : 63.4.2
pip : 22.2.2
Cython : 0.29.32
pytest : 7.1.2
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : 1.0.2
psycopg2 : 2.8.6
jinja2 : 3.1.2
IPython : 8.4.0
pandas_datareader: None
bs4 : 4.11.1
bottleneck : 1.3.5
brotli : None
fastparquet : None
fsspec : None
gcsfs : None
markupsafe : 2.1.1
matplotlib : 3.5.1
numba : 0.56.0
numexpr : 2.8.3
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : 8.0.0
pyreadstat : None
pyxlsb : None
s3fs : None
scipy : 1.8.1
snappy : None
sqlalchemy : 1.4.39
tables : None
tabulate : None
xarray : None
xlrd : None
xlwt : None
zstandard : None

@auderson auderson added Bug Needs Triage Issue that has not been reviewed by a pandas team member labels Aug 16, 2022
@auderson auderson changed the title BUG: BUG: timedelta as value to plot barplot raises error Aug 16, 2022
@dicristina
Copy link
Contributor

I get the same exception on 1.5.2 but not on master.

INSTALLED VERSIONS

commit : 2e224c7
python : 3.10.6.final.0
python-bits : 64
OS : Linux
OS-release : 5.15.0-25-generic
Version : #25-Ubuntu SMP Wed Mar 30 15:54:22 UTC 2022
machine : x86_64
processor : x86_64
byteorder : little
LC_ALL : None
LANG : en_US.UTF-8
LOCALE : en_US.UTF-8

pandas : 2.0.0.dev0+1025.g2e224c7e57
numpy : 1.23.3
pytz : 2022.2.1
dateutil : 2.8.2
setuptools : 59.6.0
pip : 22.0.2
Cython : None
pytest : 7.1.3
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : 4.9.1
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : 3.1.2
IPython : 8.5.0
pandas_datareader: None
bs4 : 4.11.1
bottleneck : None
brotli : None
fastparquet : None
fsspec : None
gcsfs : None
matplotlib : 3.6.2
numba : None
numexpr : None
odfpy : None
openpyxl : 3.0.10
pandas_gbq : None
pyarrow : None
pyreadstat : None
pyxlsb : None
s3fs : None
scipy : None
snappy : None
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
zstandard : None
tzdata : None
qtpy : 2.2.1
pyqt5 : None

@dicristina
Copy link
Contributor

The example code no longer raises an exception since the merge of #49479. Please check for the expected behavior.

@auderson
Copy link
Contributor Author

Yes, it's been solved in main branch.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug Needs Triage Issue that has not been reviewed by a pandas team member
Projects
None yet
Development

No branches or pull requests

2 participants