Select Pandas 数据框中的行,其中列值是基于两列函数的最大值

Select row in Pandas dataframe where a column value is max based on a function of two columns

我有以下数据框。

data = {'Name': ["Babu", "Shyam", "Raju", "Anuradha", "Kabira"],
       'Age': [60, 35, 32, 31, 37],
       'Income': [20000, 10000, 8000, 12000, 5000],
       'Stupidity Level': [80, 40, 60, 20, 70],
       'Expenses': [15000,8000,7000,9000,4000]
       }

index = ["Paresh Rawal", "Suniel Shetty", "Akshay Kumar","Tabu", "Gulshan Grover"]

df = pd.DataFrame(data, index)

我想找出每月存钱最多的一行(人)。

savings = df["Income"] - df["Expenses"]
savings.max()
5000

在这种情况下,它应该 return 节省最多的第一行 (5000)。但我正在尝试这样做,但实际上并没有创建一个新的储蓄专栏。所以想做一些像

df[savings.max()] # should return the row with maximum savings. 
df[(df["Income"] - df["Expenses"]).max()]

但是,当然,none 是行不通的。不确定正确的语法。

使用idxmax:

df.loc[df["Income"].sub(df["Expenses"]).idxmax()]

输出:

Name                Babu
Age                   60
Income             20000
Stupidity Level       80
Expenses           15000
Name: Paresh Rawal, dtype: object
全部最大值
s = df["Income"].sub(df["Expenses"])

out = df[s.eq(s.max())]