0

This groupby() script:

df.groupby(['period', 'tier']).type.value_counts()/df.groupby(['period']).period_days.unique()

produces this object:

    period              tier      type        
first_period_1of2   10-99_cr      tup    [35]
                    100-199_cr    tup    [34]
                    200-299_cr    tup    [18]
                    300-500_cr    tup    [17]
first_period_2of2   10-99_cr      tup    [38]
                    100-199_cr    tup    [45]
                    200-299_cr    tup    [17]
                    300-500_cr    tup    [14]
second_period_1of2  30-99_cr      tup    [35]
                    100-199_cr    tup    [46]
                    200-299_cr    tup    [18]
                    300-500_cr    tup    [25]
second_period_2of2  30-99_cr      tup    [32]
                    100-199_cr    tup    [43]
                    200-299_cr    tup    [7]
                    300-500_cr    tup    [56]
dtype: object

I would like to apply the results of the groupby() script ([35],[34],[18]...) back to the original dataframe, in a new column, assigned to the rows where the groupby() conditions are met.

df.shape
(22588, 17)

1 Answer 1

1

I think you need:

s = df.groupby(['period', 'tier']).type.value_counts()/df.groupby(['period']).period_days.unique()
df = df.join(s.rename('new'), on=['period','tier'])
Sign up to request clarification or add additional context in comments.

1 Comment

Hi @jezrael, thanks for your comment! However, I received this error message: ValueError: len(left_on) must equal the number of levels in the index of "right"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.