Transform a supported data type to a list of lists, and a list of headers, with headers padding. Supported tabular data types: * list-of-lists or another iterable of iterables * list of named tuples (usually used with headers="keys") * list of dicts (usually used with headers
(tabular_data, headers, showindex="default")
| 1457 | |
| 1458 | |
| 1459 | def _normalize_tabular_data(tabular_data, headers, showindex="default"): |
| 1460 | """Transform a supported data type to a list of lists, and a list of headers, |
| 1461 | with headers padding. |
| 1462 | |
| 1463 | Supported tabular data types: |
| 1464 | |
| 1465 | * list-of-lists or another iterable of iterables |
| 1466 | |
| 1467 | * list of named tuples (usually used with headers="keys") |
| 1468 | |
| 1469 | * list of dicts (usually used with headers="keys") |
| 1470 | |
| 1471 | * list of OrderedDicts (usually used with headers="keys") |
| 1472 | |
| 1473 | * list of dataclasses (usually used with headers="keys") |
| 1474 | |
| 1475 | * 2D NumPy arrays |
| 1476 | |
| 1477 | * NumPy record arrays (usually used with headers="keys") |
| 1478 | |
| 1479 | * dict of iterables (usually used with headers="keys") |
| 1480 | |
| 1481 | * pandas.DataFrame (usually used with headers="keys") |
| 1482 | |
| 1483 | The first row can be used as headers if headers="firstrow", |
| 1484 | column indices can be used as headers if headers="keys". |
| 1485 | |
| 1486 | If showindex="default", show row indices of the pandas.DataFrame. |
| 1487 | If showindex="always", show row indices for all types of data. |
| 1488 | If showindex="never", don't show row indices for all types of data. |
| 1489 | If showindex is an iterable, show its values as row indices. |
| 1490 | |
| 1491 | """ |
| 1492 | |
| 1493 | try: |
| 1494 | bool(headers) |
| 1495 | except ValueError: # numpy.ndarray, pandas.core.index.Index, ... |
| 1496 | headers = list(headers) |
| 1497 | |
| 1498 | err_msg = ( |
| 1499 | "\n\nTo build a table python-tabulate requires two-dimensional data " |
| 1500 | "like a list of lists or similar." |
| 1501 | "\nDid you forget a pair of extra [] or ',' in ()?" |
| 1502 | ) |
| 1503 | index = None |
| 1504 | if hasattr(tabular_data, "keys") and hasattr(tabular_data, "values"): |
| 1505 | # dict-like and pandas.DataFrame? |
| 1506 | if callable(tabular_data.values): |
| 1507 | # likely a conventional dict |
| 1508 | keys = tabular_data.keys() |
| 1509 | try: |
| 1510 | rows = list( |
| 1511 | izip_longest(*tabular_data.values()) |
| 1512 | ) # columns have to be transposed |
| 1513 | except TypeError: # not iterable |
| 1514 | raise TypeError(err_msg) |
| 1515 | |
| 1516 | elif hasattr(tabular_data, "index"): |
no test coverage detected