Home > Back-end >  How to convert dataframe into list of tuples with respect to category?
How to convert dataframe into list of tuples with respect to category?

Time:10-12

I have a following problem. I would like to convert dataframe into list of tuples based on a category. See simple code below:

data = {'product_id': ['5', '7', '8', '5', '30'], 'id_customer': ['1', '1', '1', '3', '3']}
df = pd.DataFrame.from_dict(data)

#desired output is:
result = [('5', '7', '8'), ('5', '30')]

how can I do it please? This question did not help me: Convert pandas dataframe into a list of unique tuple

CodePudding user response:

Use groupby.agg:

>>> [tuple(v) for _, v in df.groupby('id_customer')['product_id']]
[('5', '7', '8'), ('5', '30')]
>>> 

CodePudding user response:

Use GroupBy.agg with tuple like:

print (df.groupby('id_customer', sort=False)['product_id'].agg(tuple).tolist())
print (df.groupby('id_customer', sort=False)['product_id'].apply(tuple).tolist())

print (list(df.groupby('id_customer', sort=False)['product_id'].agg(tuple)))
print (list(df.groupby('id_customer', sort=False)['product_id'].apply(tuple)))
[('5', '7', '8'), ('5', '30')]
  • Related