簡體   English   中英

無法找到最大索引行的列值

[英]Unable to find column value of max index row

在熱門的UM Intro to DS in Py coursera課程中,我在第2周的任務中難以完成第二個問題。 基於以下df樣本:

      # Summer  Silver  Bronze  Total  ...  Silver.2  Bronze.2  Combined total   ID
Gold                                   ...
0           13       0       2      2  ...         0         2               2  AFG
5           12       2       8     15  ...         2         8              15  ALG
18          23      24      28     70  ...        24        28              70  ARG
1            5       2       9     12  ...         2         9              12  ARM
3            2       4       5     12  ...         4         5              12  ANZ

[5 rows x 15 columns]

問題如下:

問題1

哪個國家在夏季奧運會上獲得了最多的金牌?

此函數應返回單個字符串值。

答案是'美國'

我知道這是非常簡陋的,但我無法得到它。 很尷尬,但非常沮喪。

以下是我遇到的錯誤。

df['Gold'].argmax()
...
KeyError: 'Gold'

df['Gold'].idxmax()
...
KeyError: 'Gold'

max(df.idxmax())
...
TypeError: reduction operation 'argmax' not allowed for this dtype

df.ID.idxmax()
TypeError: reduction operation 'argmax' not allowed for this dtype

這有效,但不在函數內

df['ID'].sort_index(axis=0,ascending=False).iloc[0]

我非常感謝任何支持。

更新1感謝@Grr 成功嘗試 我仍然很好奇為什么其他方法失敗

更新2感謝@alec_djinn的第二次成功嘗試 ,這種方法類似於我之前嘗試但無法弄清楚。 謝謝!

試試這樣:

df.ID.idxmax()

這個列是你的索引有點奇怪,但是因為你可以抓住索引值等於索引最大值的行然后引用ID列。

df[df.index == df.index.max()].ID

由於KeyError您的其他方法失敗。 索引名稱為Gold ,但Gold不在列索引中,這會引發KeyError 也就是說,當'Gold'是指數時, df['Gold']是不可能的。 而是使用df.index 您也可以像這樣重置索引。

df = df.reset_index()
df

   Gold  # Summer  Silver  Bronze  Total  # Winter  Gold.1  ...  Total.1  # Games  Gold.2  Silver.2  Bronze.2  Combined total   ID
0     0        13       0       2      2         0       0  ...        0       13       0         0         2               2  AFG
1     5        12       2       8     15         3       0  ...        0       15       5         2         8              15  ALG
2    18        23      24      28     70        18       0  ...        0       41      18        24        28              70  ARG
3     1         5       2       9     12         6       0  ...        0       11       1         2         9              12  ARM
4     3         2       4       5     12         0       0  ...        0        2       3         4         5              12  ANZ

[5 rows x 16 columns]

然后您可以像之前嘗試的那樣使用df['Gold']df.Gold ,因為'Gold'現在是一個可接受的鍵。

df.Gold.idxmax()
2

在我的情況下,它的'ARG'有18枚金牌

我想你想做以下事情:

df.sort_index(ascending=False, inplace=True)
df.head(1)['ID'] #or df.iloc[0]['ID']

在一個函數中它將是:

def f(df):
    df.sort_index(ascending=False, inplace=True) #you can sort outside the function as well
    return df.iloc[0]['ID']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM