简体   繁体   English

Python pandas,如何在列中找到最大值后的最小值

[英]Python pandas, how to find the min after max in columns

I'd like to find the min value/index in the rows that are after the max value location.我想在最大值位置之后的行中找到最小值/索引。 For example:例如:

df = pd.DataFrame({"c1": [22, 55, 48, 30, 35], "c2": [6, 2, 33, 22, 17]})
df

    c1  c2
0   22  6
1   55  2
2   48  33
3   30  22
4   35  17

For c1, I need the min after max value 55, for c2, I need the min after max value 33, so the desired result should be对于 c1,我需要最大值 55 之后的最小值,对于 c2,我需要最大值 33 之后的最小值,所以期望的结果应该是

c1 30
c2 17

Obviously I could get idxmax first and pass to an apply function.显然我可以先得到 idxmax 并传递给应用程序 function。 Is there a simpler/efficient way and avoiding the apply function?有没有更简单/有效的方法并避免应用 function? I may have thousands of columns.我可能有数千列。 Appreciate the help....感谢帮助....

We can use max then do the cummax我们可以使用max然后做cummax

s=df.where(df.eq(df.max()).cummax()).min()
Out[243]: 
c1    30.0
c2    17.0
dtype: float64

Does this work?这行得通吗?

import pandas as pd

df = pd.DataFrame({"c1": [22, 55, 48, 30, 35], "c2": [6, 2, 33, 22, 17]})

col_name = 'c1'
max_index = df[col_name].argmax()
min_index = max_index + 1 + df[col_name].iloc[max_index + 1:].argmin()
df[col_name].iloc[min_index]  # 30

col_name = 'c2'
max_index = df[col_name].argmax()
min_index = max_index + 1 + df[col_name].iloc[max_index + 1:].argmin()
df[col_name].iloc[min_index]  # 17

Note that pd.Series.argmax and pd.Series.argmin return the index of the first max (or min) only.请注意pd.Series.argmaxpd.Series.argmin返回第一个最大值(或最小值)的索引。 If there are multiple max or min values, this may need to be adjusted.如果有多个最大值或最小值,则可能需要对其进行调整。

Also, this won't work if max is in the last row but we can modify it to return None or let it throw an error if that's expected.此外,如果 max 在最后一行,这将不起作用,但我们可以修改它以返回 None 或让它抛出一个错误,如果这是预期的。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM