熊猫-包含每年最大值的返回月份

时间:2018-10-17 20:22:51

标签: pandas dataframe max pandas-groupby

我有一个像这样的数据框:

$(window).load(function(){
       // possibly set radio boxes here...
       // ...or better still do everything inside the timeout function, thereby solving both problems at once:
       setTimeout(function(){ alert("I really want my page to do this"); }, 3000); 
}

我希望数据框返回最大值为每年的月份和值:

Year Month Value
2017  1     100
2017  2      1
2017  4      2
2018  3      88
2018  4      8
2019  5      87
2019  6      1

我尝试过类似year month value 2017 1 100 2018 3 88 2019 5 87 的操作,但是它返回了完整的数据集,因为每个“年/月”对都是唯一的(我相信)。

2 个答案:

答案 0 :(得分:2)

您可以使用.groupby(...).idxmax()获取最高值所在的索引,并使用它来索引原始数据帧:

In [28]: df.loc[df.groupby("Year")["Value"].idxmax()]
Out[28]:
   Year  Month  Value
0  2017      1    100
3  2018      3     88
5  2019      5     87

答案 1 :(得分:0)

以下是一种解决方案,还可以处理重复的可能性:

m = df.groupby('Year')['Value'].transform('max') == df['Value']
dfmax = df.loc[m]

完整示例:

import pandas as pd

data = '''\
Year Month Value
2017  1     100
2017  2      1
2017  4      2
2018  3      88
2018  4      88
2019  5      87
2019  6      1'''

fileobj = pd.compat.StringIO(data)
df = pd.read_csv(fileobj, sep='\s+')
m = df.groupby('Year')['Value'].transform('max') == df['Value']
print(df[m])

   Year  Month  Value
0  2017      1    100
3  2018      3     88
4  2018      4     88
5  2019      5     87
相关问题