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

mac*_*ump 4 max dataframe pandas pandas-groupby

我有一个数据框,如:

Year Month Value
2017  1     100
2017  2      1
2017  4      2
2018  3      88
2018  4      8
2019  5      87
2019  6      1
Run Code Online (Sandbox Code Playgroud)

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

year  month  value
2017    1      100
2018    3      88
2019    5      87
Run Code Online (Sandbox Code Playgroud)

df=df.groupby(["Year","Month"])['Value']).max()但是,我尝试过类似的方法,它返回完整的数据集,因为每个年/月对都是独一无二的(我相信)。

Ran*_*ndy 7

您可以获取出现最高值的索引,.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
Run Code Online (Sandbox Code Playgroud)


Ant*_*vBR 6

这是一个也处理重复可能性的解决方案:

m = df.groupby('Year')['Value'].transform('max') == df['Value']
dfmax = df.loc[m]
Run Code Online (Sandbox Code Playgroud)

完整示例:

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])
Run Code Online (Sandbox Code Playgroud)
   Year  Month  Value
0  2017      1    100
3  2018      3     88
4  2018      4     88
5  2019      5     87
Run Code Online (Sandbox Code Playgroud)