1

I have a dataframe as below where one ticket has multiple item associated with it.

| ticket_no | items |
|-----------|-------|
| 1         | Item1 |
| 1         | Item2 |
| 2         | Item3 |
| 2         | Item4 |
| 3         | Item5 |
| 3         | Item6 |
| 3         | Item7 |
| 3         | Item8 |

Need output as below.

[[Item1, Item2],[Item3, Item4], [Item5, Item6, Item7, Item8]]

I have tried below code. It works, but it is terribly slow.

data = pd.read_csv('data.csv')
item_list = []
for ticket_no in data['ticket_no'].unique():
    temp_data = list(data[data['ticket_no'] == ticket_no]['items'])
    if len(temp_data) == 1:
        pass
    else:
        item_list.append(temp_data)

Is there a faster way of doing this?

1 Answer 1

4

Use DataFrame.groupby with list to Series and then convert it to lists - output is nested lists:

item_list = data.groupby('ticket_no')['items'].apply(list).tolist()
print (item_list)
[['Item1', 'Item2'], ['Item3', 'Item4'], ['Item5', 'Item6', 'Item7', 'Item8']]
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. That works. Also, if the nested lists have only one item, I need to discard it. Can do it by looping over it but is there any other way?
@SachinPrabhu - Simpliest is filter before solution by df = df[df['ticket_no'].duplicated(keep=False)]
Worked for me. Thanks.

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.