Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import pandas as pd
- sep = ' - '
- df1 = pd.DataFrame([[1,"apple",1],[1,"banana",3],[1,"pear",2],[2,"lemon",3],[2,"orange",1],[2,"apple",2]])
- df1.columns = ["id","product","seq"]
- df1 = df1.sort_values(by=["id","seq"])
- pd.DataFrame(df1.groupby('id',as_index=False)['product'].apply(lambda x: sep.join(x)))
- df2 = df1.groupby('id',as_index=False, sort=False)['product'].apply(sep.join)
- print (df2)
- 0 apple - pear - banana
- 1 orange - apple - lemon
- dtype: object
Add Comment
Please, Sign In to add comment