piper.custom.ratio

piper.custom.ratio(value1: Union[int, float, pandas.core.series.Series], value2: Union[int, float, pandas.core.series.Series], precision: int = 2, percent: bool = False, format: bool = True)Any[source]

Calculate the Ratio / percentage of two values

Custom function which calculate the ratio and optionally percentage of two values or series.

Note

Passes back np.inf value for ‘divide by zero’ use case.

Parameters
  • value1 – integer, float, or pd.Series

  • value2 – integer, float, or pd.Series

  • precision – Default 2. Returned result is rounded to precision value.

  • percent – Default False. If True, calculates the percentage.

  • format – Default False. If True, returns a string, formatted as a percentage value e.g. 92.0%

Returns

  • float - if values1 and 2 are single int/float values

  • pd.Series - if values1 and 2 are pd.Series

Examples

s1 = pd.Series([10, 20, 30])
s2 = pd.Series([1.3, 5.4, 3])
ratio(s1, s2)

           0
   0    7.69
   1    3.70
%%piper

sample_sales()
>> select(['-target_profit', '-actual_profit'])
>> assign(std_ratio = lambda x: x.actual_sales / x.target_sales)
>> assign(ratio = lambda x: ratio(x.actual_sales, x.target_sales,
                                  percent=True, format=True, precision=4))
>> head(10)

location  product     month      target_sales  actual_sales  std_ratio   ratio
London    Beachwear   2021-01-01        31749       29209.1       0.92   92.0%
London    Beachwear   2021-01-01        37833       34049.7       0.9    90.0%
London    Jeans       2021-01-01        29485       31549         1.07   107.0%
London    Jeans       2021-01-01        37524       40901.2       1.09   109.0%
London    Sportswear  2021-01-01        27216       29121.1       1.07   107.0%