2017-08-03 59 views
1

大家好,所以我有2個數據幀我試圖合併,組中某個特定的順序:在特定的順序重新組織數據幀

df1 
    LC_REF  Category  PRDGRP 
0 17 1C  H   Ferrari,Lambo,Merc 
1 17 1C  M   Doritos,Lays,Funyun 
2 17 1C  P   Cats,Dogs,Rabbits 
3 16 2C  H   Aston,Hyundai,Honda 
4 16 2C  M   Cheeto, Vicks 
5 16 2C  P   Rat,Pig,Flamingo 
6 17 2C  M   See,Sea,Far 


df2 
    LC_REF  Category  PRDGRP 
0 17 1C   H   foo,bar 
1 17 1C   M   foo,bar1 
2 16 2C   H   foo,bar2 
3 16 2C   M   foo,bar3 
4 17 2C   H   foo,bar4 
5 17 2C   M   foo,bar5 
6 17 2C   P   foo,bar6 

我期待合併它們,這樣一個LC_REF的所有M的堆疊,然後是所有的H,然後是所有的P,然後移動到第二個LC_REF。順序無關緊要,但應保持一致。希望這是有道理的:

df3 
    LC_REF  Category  PRDGRP 
0 17 1C  M   Doritos,Lays,Funyun 
1 17 1C  M   foo,bar1 
2 17 1C  H   Ferrari,Lambo,Merc 
3 17 1C  H   foo,bar 
4 17 1C  P   Cats,Dogs,Rabbits 
5 16 2C  M   Cheeto, Vicks 
6 16 2C  M   foo,bar3 
7 16 2C  H   Aston,Hyundai,Honda 
8 16 2C  H   foo,bar4 
9 17 2C  M   See,Sea,Far 
10 17 2C  M   foo,bar5 
11 17 2C  P   foo,bar6 

我試過CONCAT的變化和追加無濟於事:

pd.concat([df1,df2]).sort_index().reset_index(drop=True) 

幾乎接近,但LC_REF亂序

回答

2

讓我們用pd.concatsort_values

df_out = pd.concat([df1,df2]) 
df_out['Category'] = df_out.Category.astype('category', categories=['M','H','P'], ordered=True) 
df_out.sort_values(by=['LC_REF','Category']) 

輸出:

LC_REF Category    PRDGRP 
4 16 2C  M  Cheeto, Vicks 
3 16 2C  M    foo,bar3 
3 16 2C  H Aston,Hyundai,Honda 
2 16 2C  H    foo,bar2 
5 16 2C  P  Rat,Pig,Flamingo 
1 17 1C  M Doritos,Lays,Funyun 
1 17 1C  M    foo,bar1 
0 17 1C  H Ferrari,Lambo,Merc 
0 17 1C  H    foo,bar 
2 17 1C  P Cats,Dogs,Rabbits 
6 17 2C  M   See,Sea,Far 
5 17 2C  M    foo,bar5 
4 17 2C  H    foo,bar4 
6 17 2C  P    foo,bar6 
+0

瘋了!我只是嘗試了類似的東西。有沒有辦法保留原來的訂單? – codeninja

+0

關閉...這是我第一次猜測。類別訂單已關閉。 –

+0

我想我不明白。 –