Use Fortran ordering to convert ndarrays and lists of iterables to lists of 1D arrays. Lists of iterables are converted by applying `numpy.asanyarray` to each of their elements. 1D ndarrays are returned in a singleton list containing them. 2D ndarrays are converted to the lis
(X, name)
| 1423 | |
| 1424 | |
| 1425 | def _reshape_2D(X, name): |
| 1426 | """ |
| 1427 | Use Fortran ordering to convert ndarrays and lists of iterables to lists of |
| 1428 | 1D arrays. |
| 1429 | |
| 1430 | Lists of iterables are converted by applying `numpy.asanyarray` to each of |
| 1431 | their elements. 1D ndarrays are returned in a singleton list containing |
| 1432 | them. 2D ndarrays are converted to the list of their *columns*. |
| 1433 | |
| 1434 | *name* is used to generate the error message for invalid inputs. |
| 1435 | """ |
| 1436 | |
| 1437 | # Unpack in case of e.g. Pandas or xarray object |
| 1438 | X = _unpack_to_numpy(X) |
| 1439 | |
| 1440 | # Iterate over columns for ndarrays. |
| 1441 | if isinstance(X, np.ndarray): |
| 1442 | X = X.transpose() |
| 1443 | |
| 1444 | if len(X) == 0: |
| 1445 | return [[]] |
| 1446 | elif X.ndim == 1 and np.ndim(X[0]) == 0: |
| 1447 | # 1D array of scalars: directly return it. |
| 1448 | return [X] |
| 1449 | elif X.ndim in [1, 2]: |
| 1450 | # 2D array, or 1D array of iterables: flatten them first. |
| 1451 | return [np.reshape(x, -1) for x in X] |
| 1452 | else: |
| 1453 | raise ValueError(f'{name} must have 2 or fewer dimensions') |
| 1454 | |
| 1455 | # Iterate over list of iterables. |
| 1456 | if len(X) == 0: |
| 1457 | return [[]] |
| 1458 | |
| 1459 | result = [] |
| 1460 | is_1d = True |
| 1461 | for xi in X: |
| 1462 | # check if this is iterable, except for strings which we |
| 1463 | # treat as singletons. |
| 1464 | if not isinstance(xi, str): |
| 1465 | try: |
| 1466 | iter(xi) |
| 1467 | except TypeError: |
| 1468 | pass |
| 1469 | else: |
| 1470 | is_1d = False |
| 1471 | xi = np.asanyarray(xi) |
| 1472 | nd = np.ndim(xi) |
| 1473 | if nd > 1: |
| 1474 | raise ValueError(f'{name} must have 2 or fewer dimensions') |
| 1475 | result.append(xi.reshape(-1)) |
| 1476 | |
| 1477 | if is_1d: |
| 1478 | # 1D array of scalars: directly return it. |
| 1479 | return [np.reshape(result, -1)] |
| 1480 | else: |
| 1481 | # 2D array, or 1D array of iterables: use flattened version. |
| 1482 | return result |
no test coverage detected
searching dependent graphs…