在python的pandas软件包中,我想分组,以便保持特定顺序。下面的代码似乎可以做到这一点,但是有没有一种更快/更简单的方法呢?还是可以保证熊猫的group by功能在源数据框中保持记录的顺序?
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)))
答案 0 :(得分:2)
使用参数sort=False
,也不需要DataFrame
建设者:
df2 = df1.groupby('id', sort=False)['product'].apply(sep.join).reset_index()
print (df2)
id product
0 1 apple - pear - banana
1 2 orange - apple - lemon