获取多列并比较的最大值并返回特定的值

2024-10-01 17:33:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个像这样的数据帧:

Sequence    Duration1   Value1  Duration2   Value2  Duration3   Value3
1001        145         10      125         53      458         33
1002        475         20      175         54      652         45
1003        685         57      687         87      254         88
1004        125         54      175         96      786         96
1005        475         21      467         32      526         32
1006        325         68      301         54      529         41
1007        125         97      325         85      872         78
1008        129         15      429         41      981         82
1009        547         47      577         52      543         83
1010        666         65      722         63      257         87

我想在(Duration1,Duration2,Duration3)中找到Duration的最大值,并返回相应的值和序列。在

我想要的输出:

^{pr2}$

Tags: 数据序列durationsequencevalue1value2pr2value3
3条回答

尝试下面的非常简短的代码,主要基于Numpy

vv = df.iloc[:, 1::2].values
iRow, iCol = np.unravel_index(vv.argmax(), vv.shape)
iCol = iCol * 2 + 1
result = df.iloc[iRow, [0, iCol, iCol + 1]]

结果是一个系列

^{pr2}$

如果要“重新绘制”它(首先是索引值,然后是实际值), 您可以执行以下操作:

pd.DataFrame([result.values], columns=result.index)

对于宽数据,使用wide_to_long可以更容易地首先重塑形状。这将创建2列['Duration', 'Value'],并且多重索引告诉我们它是哪个数字。不依赖于任何特定的列顺序。在

import pandas as pd

df = pd.wide_to_long(df, i='Sequence', j='num', stubnames=['Duration', 'Value'])
df.loc[[df.Duration.idxmax()]]

              Duration  Value
Sequence num                 
1008     3         981     82

可以使用以下方法获取列最大值的索引:

>>> idx = df['Duration3'].idxmax()
>>> idx
7

相关列仅使用:

^{pr2}$

所以,只需将所有这些都打包成一个很好的函数:

def get_max(df, i):
    idx = df[f'Duration{i}'].idxmax()
    df_cols = df[['Sequence', f'Duration{i}', f'Value{i}']]
    return df_cols.loc[idx]

并在1..3上循环:

>>> max_rows = [get_max(i) for i in range(1, 4)]
>>> print('\n\n'.join(map(str, max_rows)))
Sequence     1003
Duration1     685
Value1         57
Name: 2, dtype: int64

Sequence     1010
Duration2     722
Value2         63
Name: 9, dtype: int64

Sequence     1008
Duration3     981
Value3         82
Name: 7, dtype: int64

如果要将这3行减少到一个最大行,可以执行以下操作:

>>> pairs = enumerate(max_rows, 1)
>>> by_duration = lambda x: x[1][f'Duration{x[0]}']
>>> i, max_row = max(pairs, key=by_duration)
>>> max_row
Sequence     1008
Duration3     981
Value3         82
Name: 7, dtype: int64

相关问题 更多 >

    热门问题