[英]How do I select all rows with a minimum value that meet a condition in another column pandas
I would like to select all rows that have Points==0 and have the minimum value in the Day column from my dataset.我想 select 所有具有 Points==0 并且在我的数据集中的 Day 列中具有最小值的行。
Dataframe Dataframe
Points Day Name
55 0 Jon
0 7 Ron
0 8 Sam
44 6 Chris
0 7 Joan
49 2 Greg
What I'm hoping to get我希望得到什么
Points Day Name
0 7 Ron
0 7 Joan
I have tired this code but I only get the first instance where this is true.我已经厌倦了这段代码,但我只得到了第一个这样的例子。
df1 = df.loc[[df.loc[df.points == 0, 'Day'].idxmin()]]
How do I get all rows?如何获取所有行?
You can use the min function to get the minimum value from the filtered dataset where Points == 0 and then use it to filter the whole dataset.您可以使用 min function 从 Points == 0 的过滤数据集中获取最小值,然后使用它来过滤整个数据集。
df[(df["Points"] == 0) & (df["Day"] == min(df[df["Points"] == 0]["Day"]))]
Now it works:现在它起作用了:
>>> df
Points Day
0 55 0
1 0 7
2 0 8
3 44 6
4 0 7
5 49 2
>>> df[(df["Points"] == 0) & (df["Day"] == min(df[df["Points"] == 0]["Day"]))]
Points Day
1 0 7
4 0 7
IIUC IIUC
df.query('Points==0').loc[lambda x : x['Day']==x['Day'].min()]
Out[207]:
Points Day Name
1 0 7 Ron
4 0 7 Joan
You can do it the following way:您可以通过以下方式进行操作:
df[(df['Points']==0) & (df['Day']==df[df['Points']==0]['Day'].min())]
The & means AND in pandas boolean indexing, if you want to use OR you can use |. & 表示 pandas boolean 索引中的 AND,如果要使用 OR,可以使用 |。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.