简体   繁体   English

如何通过特定列的最大分组值过滤python数据框

[英]How to filter a python dataframe by the maximum grouped Value of a specific column

So I am try to get a df that shows the latest Price based on a grouped dataframe. 因此,我尝试获取一个基于分组数据框显示最新价格的df。 Below is a df of 9 records to help explain. 以下是9条记录的df以帮助说明。

         Country   ISO Month  Price
0        Germany   DE  201311 7.99     
1        Germany   DE  201310 8.99
2        Germany   DE  201309 6.99
3   United States  US  201310 4.99
4   United States  US  201309 11.99
5   United States  US  201308 2.99
7         France   FR  201311 7.99
8         France   FR  201310 1.99
9         France   FR  201309 1.50

I want the df to return the price that relates to the maximum Month. 我希望df返回与最大月份有关的价格。 Like to return the below view: 喜欢返回下面的视图:

         Country   ISO Month  Price
0        Germany   DE  201311 7.99     
1   United States  US  201310 4.99
2         France   FR  201311 7.99

I tried doing a groupby with a max() and could return the maximum month by doing the below 我尝试使用max()进行分组,并且可以通过以下操作返回最大月份

df.groupby(['Country','ISO'])['Month'].max().reset_index()

but the above dropped the Price out that relates to that month, and if included the 'Price' in the groupby it obviously then return all the 3 values per country as they are different values. 但是上面的方法删除了与该月相关的价格,并且如果在组中包含“价格”,则显然返回每个国家的所有3个值,因为它们是不同的值。

Sorry I couldn't find the answer i was exactly looking for after 2 hours on the net. 抱歉,在网上2个小时后我找不到确切的答案。

Is the data stored in mysql? 数据存储在mysql中吗? If the data is in a list like[(0,"Ger..","DE",201311,7.99),(....] then your goal could be achived by this code: 如果数据在[[0,“ ​​Ger ..”,“ DE”,201311,7.99),(....]等列表中,则可以通过以下代码实现目标:

the_list.sort(key=lambda x:x[3], reverse=True)[:3]

returns the data from first three largest month. 返回前三个月的数据。

Ok, using the sort and first in a groupby seemed to get the result I need. 好的,在groupby中使用sort和first似乎可以得到我需要的结果。

df.sort('Month', ascending=False).groupby(['Country','ISO'], as_index=False).first()

would return: 会返回:

         Country   ISO Month  Price
0        Germany   DE  201311 7.99     
1   United States  US  201310 4.99
2         France   FR  201311 7.99

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM