在Pandas Python中使用多个If条件从数据框中过滤值

问题描述

我正在尝试使用 if 条件检查 Test> Train 列是否为True,并检查Diff的 min 值列并返回该模型名称,但出现错误系列的真值不明确。使用a.empty,a.bool()错误。下面是我的代码和Iam正在处理的数据的屏幕截图。

#df is the dataframe name which looks like the image in the screenshot
if df['Test>Train'] == 'True' and df['Diff'] == df['Diff'].mn():
   print(Model)

随附为数据框的屏幕截图。

预先感谢

enter image description here

解决方法

尝试:

df[(df['Test>Train']=='True')&(df['Diff']==df['Diff'].min())]

但这可能不是您要寻找的(如果df['Diff'].min()为False时发生Test<Train会怎样?)。相反,我建议:

df.loc[df['Diff'].where(df['Test>Train']=='True').idxmin()]

或者根据您的数据:

s = df['Train'] - df['Test']

df.loc[s.where(s>0).idxmin()]