gpt4 book ai didi

python - pandas DataFrame.groupby 并应用自定义函数

转载 作者:太空宇宙 更新时间:2023-11-03 11:18:05 24 4
gpt4 key购买 nike

我有一个包含许多重复项的 DataFrame(我需要 Type/StrikePrice 对是唯一的),如下所示:

                   Pos  AskPrice
Type StrikePrice
C 1500.0 10 281.6
C 1500.0 11 281.9
C 1500.0 12 281.7 <- I need this one
P 1400.0 30 1200.5
P 1400.0 31 1250.2 <- I need this one

我如何按 Type + StrikePrice 进行分组并应用一些逻辑(我自己的函数)来决定从组中选择哪一行(假设是最大的 Pos)

预期的结果是

                   Pos  AskPrice
Type StrikePrice
C 1500.0 12 281.7
P 1400.0 31 1250.2

非常感谢!

最佳答案

首先 reset_index 用于唯一索引,然后是 groupbyidxmax获取每组最大值的索引并通过 loc 选择行,MultiIndex 的最后一个 set_index:

df = df.reset_index()
df = df.loc[df.groupby(['Type','StrikePrice'])['Pos'].idxmax()]
.set_index(['Type','StrikePrice'])

或者使用sort_valuesdrop_duplicates :

df = (df.reset_index()
.sort_values(['Type','StrikePrice', 'Pos'])
.drop_duplicates(['Type','StrikePrice'], keep='last')
.set_index(['Type','StrikePrice']))
print (df)

Pos AskPrice
Type StrikePrice
C 1500.0 12 281.7
P 1400.0 31 1250.2

但如果需要自定义函数使用GroupBy.apply :

def f(x):
return x[x['Pos'] == x['Pos'].max()]

df = df.groupby(level=[0,1], group_keys=False).apply(f)
print (df)
Pos AskPrice
Type StrikePrice
C 1500.0 12 281.7
P 1400.0 31 1250.2

关于python - pandas DataFrame.groupby 并应用自定义函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48478780/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com