0

My goal is to create a new column c_list that contains a list after an groupby (without merge function): df['c_list'] = df.groupby('a').agg({'c':lambda x: list(x)})

df = pd.DataFrame(
                  {'a': ['x', 'y', 'y', 'x'],
                   'b': [2, 0, 0, 0],
                   'c': [8, 2, 5, 6]
                  }
                 )
df
Initial dataframe
    a   b   c
0   x   2   8
1   y   0   2
2   y   0   5
3   x   0   6
Looking for:
    a   b   c  d
0   x   2   8  [6, 8]
1   y   0   2  [2, 5]
2   y   0   5  [2, 5]
3   x   0   6  [6, 8]

1 Answer 1

2

Try with transform

df['d']=df.groupby('a').c.transform(lambda x : [x.values.tolist()]*len(x))
0    [8, 6]
1    [2, 5]
2    [2, 5]
3    [8, 6]
Name: c, dtype: object

Or

df['d']=df.groupby('a').c.agg(list).reindex(df.a).values
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your answer. Out of curiosity, why the multiplication by len(x) in lambda function ?
@AdilBlanco transform have the problem , when there is only list , it will explode it by default, so we need the use the list multiple the len of sub-group ~

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.