我的目标是 concat() 在两个数据帧之间交替组。想要的结果: group ordercode quantity0 A 1 B 1 C 1 D 10 A 1 B 3 1 A 1 B 2 C 11 A 1 B 1 C 2我的数据框:import pandas as pddf1=pd.DataFrame([[0,"A",1],[0,"B",1],[0,"C",1],[0,"D",1],[1,"A",1],[1,"B",2],[1,"C",1]],columns=["group","ordercode","quantity"])df2=pd.DataFrame([[0,"A",1],[0,"B",3],[1,"A",1],[1,"B",1],[1,"C",2]],columns=["group","ordercode","quantity"])print(df1)print(df2)我用过 dfff=pd.concat([df1,df2]).sort_index(kind="merge")但我得到了以下结果: group ordercode quantity0 0 A 10 0 A 11 B 11 B 32 C 13 D 14 1 A 14 1 A 15 B 25 B 16 C 16 C 2您可以在这里看到连接是在每行之间形成的,而不是按组形成的。它必须像group 0 of df1 group0 of df2 group1 of df1 group1 of df2 和 so on注意:我已经使用groupby()函数创建了这些 DataFrame df = pd.DataFrame(np.concatenate(df.apply(lambda x: [x[0]] * x[1], 1).as_matrix()), columns=['ordercode'])df['quantity'] = 1df['group'] = sorted(list(range(0, len(df)//3, 1)) * 4)[0:len(df)]df=df.groupby(['group', 'ordercode']).sum() 问题:我哪里出错了?它通过取index我用过,.set_index("group")但也没有用。
查看完整描述