|
| 1 | +""" |
| 2 | +This file is part of CLIMADA. |
| 3 | +
|
| 4 | +Copyright (C) 2017 ETH Zurich, CLIMADA contributors listed in AUTHORS. |
| 5 | +
|
| 6 | +CLIMADA is free software: you can redistribute it and/or modify it under the |
| 7 | +terms of the GNU General Public License as published by the Free |
| 8 | +Software Foundation, version 3. |
| 9 | +
|
| 10 | +CLIMADA is distributed in the hope that it will be useful, but WITHOUT ANY |
| 11 | +WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A |
| 12 | +PARTICULAR PURPOSE. See the GNU General Public License for more details. |
| 13 | +
|
| 14 | +You should have received a copy of the GNU General Public License along |
| 15 | +with CLIMADA. If not, see <https://www.gnu.org/licenses/>. |
| 16 | +
|
| 17 | +--- |
| 18 | +
|
| 19 | +Define functions to handle with coordinates |
| 20 | +""" |
| 21 | + |
| 22 | +import pandas as pd |
| 23 | + |
| 24 | + |
| 25 | +def reorder_dataframe_columns( |
| 26 | + df: pd.DataFrame, priority_order: list[str], keep_remaining: bool = True |
| 27 | +) -> pd.DataFrame | pd.Series: |
| 28 | + """ |
| 29 | + Applies a column priority list to a DataFrame to reorder its columns. |
| 30 | +
|
| 31 | + This function is robust to cases where: |
| 32 | + 1. Columns in 'priority_order' are not in the DataFrame (they are ignored). |
| 33 | + 2. Columns in the DataFrame are not in 'priority_order'. |
| 34 | +
|
| 35 | + Parameters |
| 36 | + ---------- |
| 37 | + df: pd.DataFrame |
| 38 | + The input DataFrame. |
| 39 | + priority_order: list[str] |
| 40 | + A list of strings defining the desired column |
| 41 | + order. Columns listed first have higher priority. |
| 42 | + keep_remaining: bool |
| 43 | + If True, any columns in the DataFrame but NOT in |
| 44 | + 'priority_order' will be appended to the end in their |
| 45 | + original relative order. If False, these columns |
| 46 | + are dropped. |
| 47 | +
|
| 48 | + Returns: |
| 49 | + pd.DataFrame: The DataFrame with columns reordered according to the priority list. |
| 50 | + """ |
| 51 | + |
| 52 | + present_priority_columns = [col for col in priority_order if col in df.columns] |
| 53 | + |
| 54 | + new_column_order = present_priority_columns |
| 55 | + |
| 56 | + if keep_remaining: |
| 57 | + remaining_columns = [ |
| 58 | + col for col in df.columns if col not in present_priority_columns |
| 59 | + ] |
| 60 | + |
| 61 | + new_column_order.extend(remaining_columns) |
| 62 | + |
| 63 | + return df[new_column_order] |
0 commit comments