From 5cbdf48f40dc8b64335db2e33e8c43699ebd905b Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Mon, 7 Oct 2019 15:41:06 +0200 Subject: [PATCH] Simplify implementation of vectorized date operations. 1) We don't need to handle separately the scalar case -- tolist() returns a scalar when called on a 0d-array, as returned by np.vectorize() when called on a scalar. 2) We don't need to handle separately the empty case, as long as the output type ("O") is passed to np.vectorize. --- lib/matplotlib/dates.py | 26 +++++--------------------- 1 file changed, 5 insertions(+), 21 deletions(-) diff --git a/lib/matplotlib/dates.py b/lib/matplotlib/dates.py index aebfd13c3570..be9fc154bd9f 100644 --- a/lib/matplotlib/dates.py +++ b/lib/matplotlib/dates.py @@ -305,7 +305,7 @@ def _from_ordinalf(x, tz=None): # a version of _from_ordinalf that can operate on numpy arrays -_from_ordinalf_np_vectorized = np.vectorize(_from_ordinalf) +_from_ordinalf_np_vectorized = np.vectorize(_from_ordinalf, otypes="O") @cbook.deprecated( @@ -498,20 +498,11 @@ def num2date(x, tz=None): """ if tz is None: tz = _get_rc_timezone() - if not np.iterable(x): - return _from_ordinalf(x, tz) - else: - x = np.asarray(x) - if not x.size: - return x - return _from_ordinalf_np_vectorized(x, tz).tolist() - - -def _ordinalf_to_timedelta(x): - return datetime.timedelta(days=x) + return _from_ordinalf_np_vectorized(x, tz).tolist() -_ordinalf_to_timedelta_np_vectorized = np.vectorize(_ordinalf_to_timedelta) +_ordinalf_to_timedelta_np_vectorized = np.vectorize( + lambda x: datetime.timedelta(days=x), otypes="O") def num2timedelta(x): @@ -529,15 +520,8 @@ def num2timedelta(x): Returns ------- `datetime.timedelta` or list[`datetime.timedelta`] - """ - if not np.iterable(x): - return _ordinalf_to_timedelta(x) - else: - x = np.asarray(x) - if not x.size: - return x - return _ordinalf_to_timedelta_np_vectorized(x).tolist() + return _ordinalf_to_timedelta_np_vectorized(x).tolist() def drange(dstart, dend, delta):