1

I have a csv in this format

ORDER_ID    Item_DESC
 121    Beer
 121    Chips
 121    Wine
 141    Chips
 141    Wine

I need to push this out in this format:

121    Beer,Chips,Wine
141    Chips,Wine

Can somebody point me to the right direction, I have been breaking my head for a week now.

I tried the following:

Excel Pandas-Pivot,stack,melt Recursive table in SQL

Any help is appreciated.

1 Answer 1

1

You can use groupby and apply:

In [11]: df
Out[11]:
   ORDER_ID Item_DESC
0       121      Beer
1       121     Chips
2       121      Wine
3       141     Chips
4       141      Wine

In [12]: df.groupby("ORDER_ID")["Item_DESC"].apply(",".join)
Out[12]:
ORDER_ID
121         Beer,Chips,Wine
141              Chips,Wine
Name: Item_DESC, dtype: object

Then use to_csv on this result.

Sign up to request clarification or add additional context in comments.

4 Comments

Awesome and If i want to get only Item_DESC , then how do I change the code.
@sai Not quite sure I know what you mean. Do you mean do list(...).
The output from the above code comes with the ORDER_ID and then Beer,Chips,Wine. What if I dont want the order ID and only see Beer,Chips,Wine followed by Chips,Wine in the second row.
Use .to_csv(..., index=False).

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.