[英]How to return the highest value from multiple columns to a new column in a pandas df
[英]How to determine the highest value from multiple columns using Pandas
下面的代碼是我如何嘗試找出多列中的最大值,然后使用 pandas 將最大值放入新創建的列的示例。
def Alphabet (row):
AlpFields = ["A", "B", "C", "D", "E", "F"]
Alp = len(AlpFields)
AlpCheck = row[:Alp]
MaxValue = max(AlpCheck)
if MaxValue == 0:
return MaxValue, ""
return MaxValue , AlpFields[AlpCheck.index(MaxValue)]
df.apply(lambda row: Alphabet(row), axis =1)
df['HighestAlphabetScore'] = df.apply(lambda row: Alphabet(row), axis =1)
在這種情況下,我試圖找出列中的最高值:A、B、C、D、E 和 F,然后將此值放在新創建的列“最高字母分數”中。
但是,當我運行代碼時,會出現以下錯誤:
TypeError: ("'Index' object is not callable", u'發生在索引 0')
我嘗試了各種不同的方法來嘗試解決這個問題,但到目前為止沒有任何效果。 對我可能做錯的任何幫助/關於如何解決此錯誤的任何建議將不勝感激。
對於您的 dataframe df
,您可以為列軸調用max
function 並將結果分配給新列。
假設您只需要特定列中的最大值,那么代碼將是
df['HighestAlphabetScore'] = df[["A", "B", "C", "D", "E", "F"]].max(axis=1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.