gpt4 book ai didi

Python( Pandas )错误 'the label [Algeria] is not in the [index]'

转载 作者:太空宇宙 更新时间:2023-11-03 13:35:03 25 4
gpt4 key购买 nike

我不明白为什么会这样

df[(df['Gold']>0) & (df['Gold.1']>0)].loc[((df['Gold'] - df['Gold.1'])/(df['Gold'])).abs().idxmax()]

但是当我除以 (df['Gold'] + df['Gold.1'] + df['Gold.2'])它停止工作给我错误,您可以在下面找到。

有趣的是,以下行有效

df.loc[((df['Gold'] - df['Gold.1'])/(df['Gold'] + df['Gold.1'] + df['Gold.2'])).abs().idxmax()]

刚开始学Python和Pandas,不明白是怎么回事。我需要了解发生这种情况的原因以及解决方法。

错误

KeyError: 'the label [Algeria] is not in the [index]'

DataFrame 快照 enter image description here

最佳答案

你的问题是boolean indexing :

df[(df['Gold']>0) & (df['Gold.1']>0)]

返回一个过滤后的 DataFrame,它不包含您用此计算的 Seriesmax 值的 index:

((df['Gold'] - df['Gold.1'])/(df['Gold'] + df['Gold.1'] + df['Gold.2'])).abs().idxmax()

在您的数据中,它是 Algolia

所以 loc 在逻辑上会抛出一个 KeyError

一种可能的解决方案是将新过滤的DataFrame分配给df1,然后通过使用获取与Series的最大值对应的索引idxmax:

df1 = df[(df['Gold']>0) & (df['Gold.1']>0)]
df2 = df1.loc[((df1['Gold']-df1['Gold.1'])/(df1['Gold']+df1['Gold.1']+df1['Gold.2'])).abs().idxmax()]

关于Python( Pandas )错误 'the label [Algeria] is not in the [index]',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41428107/

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