2017-07-26 60 views
-1

簡單的問題在dyplr組功能的方式,我無法找到一個答案解釋分組在熊貓:爲什麼當我們組由varaibel熊貓DF,然後我們排序結果類似於R中

爲什麼我們不能像R中的組函數dplyr那樣看到分組的rosw?

對於examaple,我有這樣的數據幀:

Item  Type Price 
A   1  22 
B   1  58 
C   1  33 
A   2  80 
A   3  50 
B   2  98 
C   3  63 
B   5  8 

如果我們組由item然後Price排序,我們應該看到「A的togather,」 B的togather,兩個「C的togather哪裏這三組中的每一組都被分類。我們如何才能在python中實現這一點?

我嘗試這樣做:

df.groupby('Item').sort_values(['Price']) # This is not right becuase we can not access the sort function on the grouped by object 

df.sort_values('Price').groupby(['Item']) # This does part of the job, but I wnder why I can not see the groupped items togather? 

的產量預計將是這樣的:

Item  Type Price 
A   2  80 
A   3  50  
A   1  22 
B   2  98 
B   1  58 
B   5  8 
C   3  63 
C   1  33 
+2

你能給我們一個你預期產出的例子嗎?我很困惑,因爲你似乎交替使用「排序」和「分組」。 – MattR

+1

你需要用前面的評論提出的數據來說明所有的數據點。大多數熊貓人可能不知道dplyr的「groupby」是什麼樣子。而對於這個問題,他們可能不熟練R. – Parfait

+0

不,我不可以互換地使用它們,我正在分組然後排序。按'x'分組並按'y'排序。我希望將輸出作爲數據框按項目分組並按價格排序。 – owise

回答

1

爲了讓您的輸出,你可以使用df.sort_values

In [783]: df.sort_values(['Item', 'Price'], ascending=[True, False]) 
Out[783]: 
    Item Type Price 
3 A  2  80 
4 A  3  50 
0 A  1  22 
5 B  2  98 
1 B  1  58 
7 B  5  8 
6 C  3  63 
2 C  1  33 

一個GROUPBY不需要。