python 如何在DF中找到第一列和具有最大值的列之间的最小值?

jhkqcmku  于 2023-01-24  发布在  Python
关注(0)|答案(1)|浏览(139)

enter image description here
我想找出每一行的最大值和最大值之前的最小值。
谢谢
我尝试过使用df [“最小列”]= df.iloc[:,13:df [“最大列索引”]].idxmax(axis=1)

lqfhib0f

lqfhib0f1#

您可以使用布尔掩码来查找最大值和先前值的位置:

# get max per row
max_val = df.max(axis=1)

# identify max and values after
m1 = df.eq(max_val, axis=0)
m2 = ~m1.cummax(axis=1)

# mask values after and get min per row
min_val = df.where(m1 | m2).min(axis=1)

# update DataFrame
df['Max'] = max_val
df['MinBefore'] = min_val

输出:

ab  bc  cd  ef  eh  ij  Max  MinBefore
0   1   2  12   4   6   7   12        1.0
1   4   5   6   1  10   4   10        1.0
2   5   6   9   1   2   4    9        5.0
3  12   1   3   1   2   4   12       12.0

相关问题