|
| 1 | +# Copyright (c) 2019 pandas-gbq Authors All rights reserved. |
| 2 | +# Use of this source code is governed by a BSD-style |
| 3 | +# license that can be found in the LICENSE file. |
| 4 | + |
| 5 | +import itertools |
| 6 | + |
| 7 | +import pandas |
| 8 | + |
| 9 | + |
| 10 | +def list_columns_and_indexes(dataframe, index=True): |
| 11 | + """Return all index and column names with dtypes. |
| 12 | +
|
| 13 | + Returns: |
| 14 | + Sequence[Tuple[str, dtype]]: |
| 15 | + Returns a sorted list of indexes and column names with |
| 16 | + corresponding dtypes. If an index is missing a name or has the |
| 17 | + same name as a column, the index is omitted. |
| 18 | + """ |
| 19 | + column_names = frozenset(dataframe.columns) |
| 20 | + columns_and_indexes = [] |
| 21 | + if index: |
| 22 | + if isinstance(dataframe.index, pandas.MultiIndex): |
| 23 | + for name in dataframe.index.names: |
| 24 | + if name and name not in column_names: |
| 25 | + values = dataframe.index.get_level_values(name) |
| 26 | + columns_and_indexes.append((name, values.dtype)) |
| 27 | + else: |
| 28 | + if dataframe.index.name and dataframe.index.name not in column_names: |
| 29 | + columns_and_indexes.append( |
| 30 | + (dataframe.index.name, dataframe.index.dtype) |
| 31 | + ) |
| 32 | + |
| 33 | + columns_and_indexes += zip(dataframe.columns, dataframe.dtypes) |
| 34 | + return columns_and_indexes |
| 35 | + |
| 36 | + |
| 37 | +def first_valid(series): |
| 38 | + first_valid_index = series.first_valid_index() |
| 39 | + if first_valid_index is not None: |
| 40 | + return series.at[first_valid_index] |
| 41 | + |
| 42 | + |
| 43 | +def first_array_valid(series): |
| 44 | + """Return the first "meaningful" element from the array series. |
| 45 | +
|
| 46 | + Here, "meaningful" means the first non-None element in one of the arrays that can |
| 47 | + be used for type detextion. |
| 48 | + """ |
| 49 | + first_valid_index = series.first_valid_index() |
| 50 | + if first_valid_index is None: |
| 51 | + return None |
| 52 | + |
| 53 | + valid_array = series.at[first_valid_index] |
| 54 | + valid_item = next((item for item in valid_array if not pandas.isna(item)), None) |
| 55 | + |
| 56 | + if valid_item is not None: |
| 57 | + return valid_item |
| 58 | + |
| 59 | + # Valid item is None because all items in the "valid" array are invalid. Try |
| 60 | + # to find a true valid array manually. |
| 61 | + for array in itertools.islice(series, first_valid_index + 1, None): |
| 62 | + try: |
| 63 | + array_iter = iter(array) |
| 64 | + except TypeError: |
| 65 | + continue # Not an array, apparently, e.g. None, thus skip. |
| 66 | + valid_item = next((item for item in array_iter if not pandas.isna(item)), None) |
| 67 | + if valid_item is not None: |
| 68 | + break |
| 69 | + |
| 70 | + return valid_item |
0 commit comments