|
| 1 | +"""Reproduce the functionality of the default round function from Excel or SAS, rounding data up to a given number of decimal places. |
| 2 | +
|
| 3 | +Instead of Python's default of rounding to even. |
| 4 | +""" |
| 5 | + |
| 6 | +from decimal import ROUND_HALF_UP, Decimal, localcontext |
| 7 | +from typing import TYPE_CHECKING, Any, overload |
| 8 | + |
| 9 | +import pandas as pd |
| 10 | + |
| 11 | + |
| 12 | +# Alias for type checking |
| 13 | +if TYPE_CHECKING: |
| 14 | + pd_Series = pd.Series[Any] |
| 15 | +else: |
| 16 | + pd_Series = ( |
| 17 | + object # Fallback to avoid runtime issues where pd.Series is not subscriptable |
| 18 | + ) |
| 19 | + |
| 20 | + |
| 21 | +# Overloads, output type is dependent on input type |
| 22 | +@overload |
| 23 | +def round_up(data: pd.DataFrame, decimal_places: int) -> pd.DataFrame: ... |
| 24 | +@overload |
| 25 | +def round_up(data: pd_Series, decimal_places: int) -> pd_Series: ... |
| 26 | + |
| 27 | + |
| 28 | +# Mypy does not like getting specific with Literal[0], thats too bad |
| 29 | +@overload |
| 30 | +def round_up(data: int | float, decimal_places: int) -> int | float: ... |
| 31 | +@overload |
| 32 | +def round_up( |
| 33 | + data: pd._libs.missing.NAType, decimal_places: int |
| 34 | +) -> pd._libs.missing.NAType: ... |
| 35 | + |
| 36 | + |
| 37 | +def round_up( |
| 38 | + data: pd.DataFrame | pd_Series | float | pd._libs.missing.NAType, |
| 39 | + decimal_places: int = 0, |
| 40 | + col_names: str | list[str] | dict[str, int] = "", |
| 41 | +) -> pd.DataFrame | pd_Series | int | float | pd._libs.missing.NAType: |
| 42 | + """Round up a number, to a given number of decimal places. Avoids Pythons default of rounding to even. |
| 43 | +
|
| 44 | + Args: |
| 45 | + data: The data to round up, can be a float, Series, or DataFrame. |
| 46 | + decimal_places: The number of decimal places to round up to. Ignored if you send a dictionary into col_names with column names and decimal places. |
| 47 | + col_names: The column names to round up. If a dictionary is provided, it should map column names to the number of decimal places for each column. |
| 48 | + If a list is provided, it should contain the names of the columns to round up. If a string is provided, it should be the name of a single column to round up. |
| 49 | +
|
| 50 | + Returns: |
| 51 | + pd.DataFrame | pd.Series | int | float: The rounded up number as an int, float, Series, or DataFrame. |
| 52 | +
|
| 53 | + Raises: |
| 54 | + TypeError: If data is not a DataFrame, Series, int, float, or NAType. |
| 55 | + """ |
| 56 | + if isinstance(data, pd.DataFrame): |
| 57 | + if isinstance(col_names, dict): |
| 58 | + # Assuming col_names is a dictionary with column names as keys and decimal places as values |
| 59 | + for col, dec in col_names.items(): |
| 60 | + data = _apply_rounding_to_df_col(data, col, dec) |
| 61 | + elif isinstance(col_names, list): |
| 62 | + # Assuming col_names is a list of column names |
| 63 | + for col in col_names: |
| 64 | + data = _apply_rounding_to_df_col(data, col, decimal_places) |
| 65 | + elif isinstance(col_names, str): |
| 66 | + # Assuming col_names is a single column name |
| 67 | + data = _apply_rounding_to_df_col(data, col_names, decimal_places) |
| 68 | + elif isinstance(data, pd.Series): |
| 69 | + # If data is a Series, round it directly |
| 70 | + data = _set_dtype_from_decimal_places( |
| 71 | + data.apply(_round, decimals=decimal_places), decimal_places |
| 72 | + ) |
| 73 | + elif isinstance(data, int | float | pd._libs.missing.NAType): |
| 74 | + data = _round(data, decimals=decimal_places) |
| 75 | + else: |
| 76 | + raise TypeError( |
| 77 | + "data must be a DataFrame, Series, int, float, or NAType. " |
| 78 | + f"Got {type(data)} instead." |
| 79 | + ) |
| 80 | + return data |
| 81 | + |
| 82 | + |
| 83 | +def _apply_rounding_to_df_col( |
| 84 | + df: pd.DataFrame, col_name: str, decimal_places: int |
| 85 | +) -> pd.DataFrame: |
| 86 | + """Apply rounding to a specific column in a DataFrame. |
| 87 | +
|
| 88 | + Args: |
| 89 | + df: The DataFrame to round. |
| 90 | + col_name: The name of the column to round. |
| 91 | + decimal_places: The number of decimal places to round to. |
| 92 | +
|
| 93 | + Returns: |
| 94 | + pd.DataFrame: The DataFrame with the rounded column. |
| 95 | + """ |
| 96 | + if col_name in df.columns: |
| 97 | + df[col_name] = _set_dtype_from_decimal_places( |
| 98 | + df[col_name].apply(_round, decimals=decimal_places), decimal_places |
| 99 | + ) |
| 100 | + return df |
| 101 | + |
| 102 | + |
| 103 | +def _set_dtype_from_decimal_places( |
| 104 | + data: pd_Series, |
| 105 | + decimal_places: int = 0, |
| 106 | +) -> pd_Series: |
| 107 | + """Set the dtype of the data based on the number of decimal places. |
| 108 | +
|
| 109 | + Args: |
| 110 | + data: The column to set the dtype for. |
| 111 | + decimal_places: The number of decimal places. |
| 112 | +
|
| 113 | + Returns: |
| 114 | + pd_Series: The data with the updated dtype. |
| 115 | + """ |
| 116 | + if decimal_places == 0: |
| 117 | + return data.astype("Int64") |
| 118 | + else: |
| 119 | + return data.astype("Float64") |
| 120 | + |
| 121 | + |
| 122 | +def _round( |
| 123 | + n: float | pd._libs.missing.NAType, |
| 124 | + decimals: int = 0, |
| 125 | +) -> float | int | pd._libs.missing.NAType: |
| 126 | + if pd.isna(n): |
| 127 | + return pd.NA |
| 128 | + elif n or n == 0: |
| 129 | + with localcontext() as ctx: |
| 130 | + ctx.rounding = ROUND_HALF_UP |
| 131 | + rounded = round(Decimal(n), decimals) |
| 132 | + if decimals == 0: |
| 133 | + return int(Decimal(rounded).to_integral_value()) |
| 134 | + return float(rounded) |
| 135 | + return n |
0 commit comments