我想要获取dataframe中某列的日期和最大值,但如果有多个记录,我希望所有记录都具有最大值。当我这样做的时候,我只能得到第一条记录:
df_max = df.loc[df.groupby('date')['quantity'].idxmax]发布于 2021-03-20 10:09:42
尝试使用transform
df_max = df.loc[df.groupby('date')['quantity'].transform('max') ==df['quantity'] ]发布于 2021-03-20 10:22:09
我能够得到所有的行。这是我所做的。
import pandas as pd
df = pd.DataFrame({"date":['2021-01-01','2021-01-01','2021-01-01','2021-01-01',
'2021-01-02','2021-01-02','2021-01-03','2021-01-03'],
"quantity":[11, 2, 5, 8, 11, 8, 11, 4]})
print (df)
dfmax = df.loc[df.groupby('date')['quantity'].idxmax()]
print (dfmax)原始DataFrame:
date quantity
0 2021-01-01 11
1 2021-01-01 2
2 2021-01-01 5
3 2021-01-01 8
4 2021-01-02 11
5 2021-01-02 8
6 2021-01-03 11
7 2021-01-03 4使用idxmax的最大值:
date quantity
0 2021-01-01 11
4 2021-01-02 11
6 2021-01-03 11发布于 2021-03-20 10:28:55
下面是一个如何使用apply完成此操作的示例
dfmax = df[df.groupby('date')['quantity'].apply(lambda x: x==x.max())]https://stackoverflow.com/questions/66717611
复制相似问题