How to calculate ratio from two different pandas dataframe

user6083088

I'm trying to calculate sales ratio of retailer-sku across a period of weeks and then calculate the mean of retailer-sku across those weeks.

So far I've been able to calculate the sum of sales across weeks for sku's and then I have grouped the sales of retailer-sku across weeks.

Now I'm unable to find the way to calculate the ratio of sales across 'N' number of weeks of retailer sku.

Here is my code

score_period = [
        [201636, 201643],
        [201640, 201647],
        [201645, 201652],
        [201649, 201704],
        [201701, 201708]
    ]


    sku_group = df.groupby('Sku', as_index=False)
    sku_list = sku_group.groups.keys()

    for sku in sku_list:

        df_sku = df[df['Sku'] == sku]
        for period in score_period:
            df_period = df_sku[(df_sku['Week'] >= period[0]) &
                               (df_sku['Week'] <= period[1])]

            # sales of each week in period
            df_sum = df_period.groupby(['Week'], as_index=False)['WeekSales'].sum()
            # retailer sales sum per week
            sums = df_period.groupby(['Week', 'RetailerCode'], as_index=False)['WeekSales'].sum()

            for index, rows in sums.iterrows():
                sums['ratio'] = sums['WeekSales'] / df_sum[(df_sum['Week'])]['WeekSales']

Data

sales = [
    {'RetailerCode': 'RET001', 'Sku': 'SKU001', 'Week': 201636, 'WeekSales': 10},
    {'RetailerCode': 'RET002', 'Sku': 'SKU002', 'Week': 201636, 'WeekSales': 20},
    {'RetailerCode': 'RET003', 'Sku': 'SKU003', 'Week': 201636, 'WeekSales': 0},
    {'RetailerCode': 'RET004', 'Sku': 'SKU004', 'Week': 201636, 'WeekSales': 10},
    {'RetailerCode': 'RET001', 'Sku': 'SKU001', 'Week': 201637, 'WeekSales': 5},
    {'RetailerCode': 'RET002', 'Sku': 'SKU002', 'Week': 201637, 'WeekSales': 10},
    {'RetailerCode': 'RET003', 'Sku': 'SKU003', 'Week': 201637, 'WeekSales': 20},
    {'RetailerCode': 'RET004', 'Sku': 'SKU004', 'Week': 201637, 'WeekSales': 3},
]

df = pd.DataFrame(sales)

Expected results:

RET001 avg ratio = (Ratio of first week + Ratio of second week) / 2
RET002 avg ratio = (Ratio of first week + Ratio of second week) / 2
Tien Liang

Explanation

  • At the last for-loop, you should access rows, not sums (whole table).

  • Because you are iterate through the tables, you can not add column simply by sum['ratio']. You have to use sums.loc[index, 'ratio'] (Explanation of this can be found here)

  • To match the week in df_sum and sums, you need to do df_sum[df_sum['Week'] == rows['Week']. This will return value of WeekSales in df_sum that matches Week in current row.

Please check if the below code is what you are looking for.

score_period = [
    [201636, 201643],
    [201640, 201647],
    [201645, 201652],
    [201649, 201704],
    [201701, 201708]
]
sku_group = df.groupby('Sku', as_index=False)
sku_list = sku_group.groups.keys()


sku_group = df.groupby('Sku', as_index=False)
sku_list = sku_group.groups.keys()
#for sku in sku_list:
#  df_sku = df[df['Sku'] == sku]
for period in score_period:
    df_period = df[(df['Week'] >= period[0]) & (df['Week'] <= period[1])]

    # sales of each week in period
    df_sum = df_period.groupby(['Week'], as_index=False)['WeekSales'].sum()
    # retailer sales sum per week
    sums = df_period.groupby(['Week', 'RetailerCode'], as_index=False)['WeekSales'].sum()
    for index, rows in sums.iterrows():
        sums.loc[index,'ratio'] = (rows['WeekSales']/df_sum[df_sum['Week']==rows['Week']]['WeekSales']).values

Result:

     Week RetailerCode  WeekSales     ratio
0  201636       RET001         10  0.250000
1  201636       RET002         20  0.500000
2  201636       RET003          0  0.000000
3  201636       RET004         10  0.250000
4  201637       RET001          5  0.131579
5  201637       RET002         10  0.263158
6  201637       RET003         20  0.526316
7  201637       RET004          3  0.078947

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

pandas how to divide to get ratio for different two dataframe

From Dev

How to calculate ratio of values in a pandas dataframe column?

From Dev

Calculate a new pandas DataFrame from two dataframes

From Dev

pandas for each group calculate ratio of two categories, and append as a new column to dataframe using .pipe()

From Dev

Calculate a ratio from two MySQL SELECT statements

From Dev

Generate two columns from three different tables and calculate the ratio of those columns using a grouping variable

From Dev

How to create a ratio score from values in a pandas DataFrame?

From Java

How to calculate the ratio using two hashmaps in java

From Dev

How to aggregate two numerical variables then calculate the ratio

From Dev

How to calculate cumulative sum from different columns based on months using pandas dataframe?

From Dev

How to calculate QTD values from different columns based on months in a pandas dataframe?

From Dev

How Do I Create New Column In Pandas Dataframe Using Two Columns Simultaneously From A Different Dataframe?

From Dev

Calculate ratio two tables

From Dev

How to calculate ranking based on two different attributes from two tables?

From Dev

how to calculate the total of two incremented values from two different loops?

From Dev

How to calculate number of years between two dates in different pandas columns

From Dev

How to calculate the distance between latitudes and longitudes of two stations in a pandas dataframe

From Dev

How to get only different words from two pandas.DataFrame columns

From Dev

How to plot different groups from a pandas dataframe

From Dev

How two compare two rows from two different dataframes pandas

From Dev

How to calculate Sum and Subtraction from two different table

From Dev

how to calculate month difference from two different columns in Sql Developer?

From Dev

two plots from pandas dataframe with different vertical axes on the same figure

From Dev

compare two value from different dataframe and based on that add value in pandas

From Dev

Calculate pvalue from pandas DataFrame

From Dev

How can I calculate the sum of two `pandas.DataFrame` based on `pandas.DataFrame.index`?

From Javascript

How to programmatically calculate the contrast ratio between two colors?

From Dev

How to calculate a ratio of two dataframes with unevenly spaced values in R?

From Dev

How do I calculate the ratio of two values within a SQL group?

Related Related

  1. 1

    pandas how to divide to get ratio for different two dataframe

  2. 2

    How to calculate ratio of values in a pandas dataframe column?

  3. 3

    Calculate a new pandas DataFrame from two dataframes

  4. 4

    pandas for each group calculate ratio of two categories, and append as a new column to dataframe using .pipe()

  5. 5

    Calculate a ratio from two MySQL SELECT statements

  6. 6

    Generate two columns from three different tables and calculate the ratio of those columns using a grouping variable

  7. 7

    How to create a ratio score from values in a pandas DataFrame?

  8. 8

    How to calculate the ratio using two hashmaps in java

  9. 9

    How to aggregate two numerical variables then calculate the ratio

  10. 10

    How to calculate cumulative sum from different columns based on months using pandas dataframe?

  11. 11

    How to calculate QTD values from different columns based on months in a pandas dataframe?

  12. 12

    How Do I Create New Column In Pandas Dataframe Using Two Columns Simultaneously From A Different Dataframe?

  13. 13

    Calculate ratio two tables

  14. 14

    How to calculate ranking based on two different attributes from two tables?

  15. 15

    how to calculate the total of two incremented values from two different loops?

  16. 16

    How to calculate number of years between two dates in different pandas columns

  17. 17

    How to calculate the distance between latitudes and longitudes of two stations in a pandas dataframe

  18. 18

    How to get only different words from two pandas.DataFrame columns

  19. 19

    How to plot different groups from a pandas dataframe

  20. 20

    How two compare two rows from two different dataframes pandas

  21. 21

    How to calculate Sum and Subtraction from two different table

  22. 22

    how to calculate month difference from two different columns in Sql Developer?

  23. 23

    two plots from pandas dataframe with different vertical axes on the same figure

  24. 24

    compare two value from different dataframe and based on that add value in pandas

  25. 25

    Calculate pvalue from pandas DataFrame

  26. 26

    How can I calculate the sum of two `pandas.DataFrame` based on `pandas.DataFrame.index`?

  27. 27

    How to programmatically calculate the contrast ratio between two colors?

  28. 28

    How to calculate a ratio of two dataframes with unevenly spaced values in R?

  29. 29

    How do I calculate the ratio of two values within a SQL group?

HotTag

Archive