简体   繁体   English

根据两列的函数在 Pandas 数据框中选择列值最大的行

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

I have the following dataframe.我有以下数据框。

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)

在此处输入图像描述

I am trying to find out a row (person) who saves maximum amount every month.我试图找出每个月节省最大金额的行(人)。

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

In this case, it should return the first row whose savings is maximum (5000).在这种情况下,它应该返回节省最大 (5000) 的第一行。 But I am trying to this without actually creating a new column for savings.但我正在尝试这样做,但实际上并没有创建一个新的储蓄列。 So want to do something like所以想做类似的事情

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

But of course, none of this isn't working.但是,当然,这些都行不通。 Not sure of the correct synatax.不确定正确的语法。

Use idxmax :使用idxmax

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

output:输出:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 基于两列 A、B 从数据框中删除重复项,在另一列 C 中保留具有最大值的行 - Remove duplicates from dataframe, based on two columns A,B, keeping row with max value in another column C 根据列的最大值删除pandas数据帧行 - Drop pandas dataframe row based on max value of a column Select Pandas dataframe 行,其中两列或多列一起具有最大值 - Select Pandas dataframe row where two or more columns have their maximum value together Pandas dataframe select 列基于其他 Z6A8064B5DF479455500553 列中的值47DC - Pandas dataframe select Columns based on other dataframe contains column value in it 如何在不使用where函数的情况下基于pandas DataFrame下的其他列有条件地选择列? - How to conditionally select column based on other columns under pandas DataFrame without using where function? Select a pandas dataframe 行,其中列具有最小值 - Select a pandas dataframe row where column has minimum value 根据熊猫列中的值从DataFrame中选择特定的行 - Select particular row from a DataFrame based on value in a column in pandas 根据列中的最大值过滤DataFrame - Pandas - Filter DataFrame based on Max value in Column - Pandas Select pandas dataframe 其中行和列== 0到F - Select pandas dataframe where row and column== 0 to F 基于行和多列的pandas dataframe列 - pandas dataframe column based on row and multiple columns
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM