![](/img/trans.png)
[英]Find the unique values of the first column but not present in the second column and return the corresponding row number of the value in first column
[英]Find maximum value of a column and return the corresponding row values using Pandas
使用 Python Pandas 我試圖找到具有最大值的Country
和Place
。
這將返回最大值:
data.groupby(['Country','Place'])['Value'].max()
但是我如何獲得相應的Country
和Place
?
假設df
有一個唯一索引,這給出了具有最大值的行:
In [34]: df.loc[df['Value'].idxmax()]
Out[34]:
Country US
Place Kansas
Value 894
Name: 7
請注意, idxmax
返回索引標簽。 所以如果DataFrame在索引中有重復,標簽可能不會唯一標識該行,因此df.loc
可能會返回多於一行。
因此,如果df
沒有唯一索引,則必須在進行上述操作之前使索引唯一。 根據 DataFrame 的不同,有時您可以使用stack
或set_index
使索引唯一。 或者,您可以簡單地重置索引(因此行重新編號,從 0 開始):
df = df.reset_index()
df[df['Value']==df['Value'].max()]
這將返回具有最大值的整行
我認為返回具有最大值的行的最簡單方法是獲取其索引。 argmax()
可用於返回具有最大值的行的索引。
index = df.Value.argmax()
現在可以使用索引來獲取該特定行的特征:
df.iloc[df.Value.argmax(), 0:2]
country 和 place 是系列的索引,如果不需要索引,可以設置as_index=False
:
df.groupby(['country','place'], as_index=False)['value'].max()
編輯:
似乎您想要每個國家/地區都具有最大值的地方,以下代碼將執行您想要的操作:
df.groupby("country").apply(lambda df:df.irow(df.value.argmax()))
使用DataFrame
的index
屬性。 請注意,我沒有鍵入示例中的所有行。
In [14]: df = data.groupby(['Country','Place'])['Value'].max()
In [15]: df.index
Out[15]:
MultiIndex
[Spain Manchester, UK London , US Mchigan , NewYork ]
In [16]: df.index[0]
Out[16]: ('Spain', 'Manchester')
In [17]: df.index[1]
Out[17]: ('UK', 'London')
您還可以通過該索引獲取值:
In [21]: for index in df.index:
print index, df[index]
....:
('Spain', 'Manchester') 512
('UK', 'London') 778
('US', 'Mchigan') 854
('US', 'NewYork') 562
抱歉誤解了您想要的內容,請嘗試以下操作:
In [52]: s=data.max()
In [53]: print '%s, %s, %s' % (s['Country'], s['Place'], s['Value'])
US, NewYork, 854
為了打印具有最大值的國家和地區,請使用以下代碼行。
print(df[['Country', 'Place']][df.Value == df.Value.max()])
您可以使用:
print(df[df['Value']==df['Value'].max()])
我在列中查找最大值的解決方案:
df.ix[df.idxmax()]
, 也是最小值:
df.ix[df.idxmin()]
我建議使用nlargest
以獲得更好的性能和更短的代碼。 進口pandas
df[col_name].value_counts().nlargest(n=1)
進口大熊貓
df 是您創建的數據框。
使用命令:
df1=df[['Country','Place']][df.Value == df['Value'].max()]
這將顯示值最大的國家和地點。
我在嘗試使用 Pandas 導入數據時遇到了類似的錯誤,數據集的第一列在單詞開始前有空格。 我刪除了空格,它就像一個魅力!
DataFrame.nlargest
。 對此的專用方法是nlargest
,它在后台使用algorithm.SelectNFrame
,這是一種sort_values().head(n)
方法: sort_values().head(n)
x y a b
0 1 2 a x
1 2 4 b x
2 3 6 c y
3 4 1 a z
4 5 2 b z
5 6 3 c z
df.nlargest(1, 'y')
x y a b
2 3 6 c y
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.