From 71fbadbbdd04460de6e9aa88221742af1ba619db Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Sat, 18 Feb 2017 02:14:51 -0800 Subject: [PATCH] Simplify _reshape_2D. (I still think iterating over rows vs. over columns depending on input type is rather silly but at least this implementation makes it clearer.) --- lib/matplotlib/cbook/__init__.py | 34 +++++++++----------------------- 1 file changed, 9 insertions(+), 25 deletions(-) diff --git a/lib/matplotlib/cbook/__init__.py b/lib/matplotlib/cbook/__init__.py index 5016ef429607..e6f5866f2a77 100644 --- a/lib/matplotlib/cbook/__init__.py +++ b/lib/matplotlib/cbook/__init__.py @@ -1983,32 +1983,16 @@ def _reshape_2D(X): v is iterable and can be used to instantiate a 1D array. """ - if hasattr(X, 'shape'): - # one item - if len(X.shape) == 1: - if hasattr(X[0], 'shape'): - X = list(X) - else: - X = [X, ] - - # several items - elif len(X.shape) == 2: - nrows, ncols = X.shape - if nrows == 1: - X = [X] - elif ncols == 1: - X = [X.ravel()] - else: - X = [X[:, i] for i in xrange(ncols)] - else: - raise ValueError("input `X` must have 2 or fewer dimensions") - - if not hasattr(X[0], '__len__'): - X = [X] + # Iterate over columns for ndarrays, over rows otherwise. + X = X.T if isinstance(X, np.ndarray) else np.asarray(X) + if X.ndim == 1 and X.dtype.type != np.object_: + # 1D array of scalars: directly return it. + return [X] + elif X.ndim in [1, 2]: + # 2D array, or 1D array of iterables: flatten them first. + return [np.reshape(x, -1) for x in X] else: - X = [np.ravel(x) for x in X] - - return X + raise ValueError("input `X` must have 2 or fewer dimensions") def violin_stats(X, method, points=100):