gpt4 book ai didi

python - 循环遍历具有多个条件的分组数据框

转载 作者:行者123 更新时间:2023-12-01 07:45:26 24 4
gpt4 key购买 nike

我得到了一个 csv 文件,如下表所示。对于每个文件夹,我希望返回成为“狗”的概率最高的图像。每个文件夹只能返回一张图像。如果 Dog 不存在,则将概率最高的“Cat”设为主要图像。如果没有猫,则将概率最大的鸟设为主图像,依此类推。

CSV:

FolderName     ImageName    Predictions    Probabilities
ABC MyPet Dog 0.98
ABC HisPet Cat 0.90
DEF HerPet Bird 0.83
ABC NotPet Dog 0.23
DEF asdf Dog 0.78
DEF M123 Cat 0.19
GHI M123s Cat 0.89
GHI M13 Cat 0.19

我只能返回概率最高的 img,如何才能优先考虑预测列然后是概率列?

df.loc[df.groupby('FolderName')['Probabilities'].idxmax()]

代码返回

FolderName     ImageName    Predictions    Probabilities
ABC MyPet Dog 0.98
DEF asdf Bird 0.83
GHI M123s Cat 0.89

期望的结果:

FolderName     ImageName    Predictions    Probabilities
ABC MyPet Dog 0.98
DEF asdf Dog 0.78
GHI M123s Cat 0.89

最佳答案

这可以通过将“预测”转换为有序分类列,然后调用 sort_valuesdrop_duplicates 来完成。

df['Predictions'] = pd.Categorical(
df['Predictions'], categories=['Dog', 'Cat', 'Bird'], ordered=True)

(df.sort_values(['Predictions', 'Probabilities'], ascending=[True, False])
.drop_duplicates('FolderName'))

FolderName ImageName Predictions Probabilities
0 ABC MyPet Dog 0.98
4 DEF asdf Dog 0.78
6 GHI M123s Cat 0.89

关于python - 循环遍历具有多个条件的分组数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56486530/

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