0

I have a df with three columns no , name, date . If no and date are matched thier value will be added in output column to a list.

Ex: 1234 and 2 matched from 0 and 1 rows - so [a,b]

If no and date doesn't match add the same name value to list

      no       name   date

0   1234        a       2

1   1234        b       2

2   1234        c       3

3   456         d       1

4   456         e       2  

5   789         f       5

Resultant Output.

      no       name   date    output

0   1234        a       2     [a,b]

1   1234        b       2     [a,b]

2   1234        c       3      [c]

3   456         d       1      [d]

4   456         e       2      [e]

5   789         f       5      [f]
1

2 Answers 2

1

Another solution would be to combine groupby and transform with sum and list. You'd have to see about the performance though.

df['output'] = df.groupby(['no', 'date'])['name'].transform(sum).apply(list)

     no name date  output
0  1234    a    2  [a, b]
1  1234    b    2  [a, b]
2  1234    c    3     [c]
3   456    d    1     [d]
4   456    e    2     [e]
5   789    f    5     [f]
Sign up to request clarification or add additional context in comments.

Comments

0

You can try groupby.agg(list) to get the list for each combination of no and date, then merge to assign back:

df.merge(df.groupby(['no','date'])['name']
           .agg(list).rename('output'),
         on=['no', 'date']
        )

Output:

     no name  date  output
0  1234    a     2  [a, b]
1  1234    b     2  [a, b]
2  1234    c     3     [c]
3   456    d     1     [d]
4   456    e     2     [e]
5   789    f     5     [f]

Comments

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.