Change this table structure formarket basket analysis

27 Views Asked by At

my code:

basket = response.groupby('user_id')[['call', 'signal','others']].apply(list) 
basket

what I get:

user_id

1        [call, signal,others]
2        [call, signal,others]
3        [call, signal,others]
4        [call, signal,others]

but I want to create a column with name 'final' and all values in the call, signal,others will look like a list.

see what I want

user_id  final
1        [A, B,C]
2        [A, B]
3        [B]
4        [B]

NO DUPLICATE ON EACH USER ROW i.e [A,A,B,B, C]

1

There are 1 best solutions below

2
Mahboob Nur On BEST ANSWER

As you didn't provide the input data, it was hard to resolve the output. Some how I manage to come up with the solution

import pandas as pd
data = {
    'user_id': [1, 2, 3, 4],
    'call': ['A', 'A', 'B', 'B'],
    'signal': ['B', 'B', 'B', 'B'],
    'others': ['C', 'A', 'B', 'B']
}
response = pd.DataFrame(data)
basket = response.groupby('user_id')[['call', 'signal', 'others']].apply(lambda x: list(dict.fromkeys(x.values.ravel())))
basket = basket.reset_index(name='final')
print(basket)

My Output