2017-07-26 59 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不需要。