簡體   English   中英

如何在Python的多列中從行組中找到2個最大值,並顯示其行和列索引而沒有重復項

[英]How to find 2 largest values from group of rows in multiple columns in Python and also show its row and column index without duplicates

我是Python的新手。 我想從所有列中找到重復行元素的最大值(即5到150),並在輸出中顯示其行和列索引標簽。最大值應為絕對值。 (與+或-無關)。 行索引組將繼續重復'n'次。 對於行索引的每個“第n個”組,我希望每個組具有“ n”個最大值及其索引位置。 同樣,如果在不同的組中重復某個索引的最大值,則程序必須將該索引分配給兩個值最大的組。 不同組中的行索引不應重復。

我的數據集: Mydataset

df=pd.DataFrame({'0_deg': [43, 50, 45, -17, 5, 8, 9, 19, 11, 32, 36, 41, 10, 1, 19, 11, 32, 36, 1, 8, 9], 
              '10_deg': [47, 41, 46, -18, 4, 5, 11, 16, 12, 34, -52, 31, 23, 4, 16, 12, 34, -71, 2, 7, 10], 
              '20_deg': [46, 43, -56, 29, 6, 7, 10, 14, 13, 33, 43, 6, 9, -40, 14, 13, 37, 43, 3, 6, 11], 
              '30_deg': [-46, 16, -40, -11, 9, 1, 12, 15, 33, -39, -22, 21, 23, 14, 15, 63, -39, -22, 4, 5, 12]}, index=[5, 10, 12, 101, 130, 140, 150, 5, 10, 12, 101, 130, 140, 150, 5, 10, 12, 101, 130, 140, 150])

df = df.set_index('Number')
def f(x):
    x1 = x.abs().stack()
    x2 = x.stack()
    x = x2.iloc[np.argsort(-x1)].head(b)
    return x

groups = (df.index == 5).cumsum()
df1 = df.groupby(groups).apply(f).reset_index(level=[1,2])
df1.columns = ['Number','Angle','Value']
print (df1)

預期結果:

Expectedoutput

實際結果:

Actualoutput

您可能需要兩個groupby過濾器

df = df.reset_index()
df['key']=df['index'].eq(5).cumsum()
s=df.melt(['key','index'])
s=s[(-s.value.abs()).groupby(s['index']).rank()==1]
# just need select max row of each index before pick two from the each group
s[(-s.value.abs()).groupby(s.key).rank()<=2].sort_values('key')
Out[672]: 
    key  index variable  value
21    1      5   10_deg     47
44    1     12   20_deg    -56
11    2    130    0_deg     41
55    2    150   20_deg    -40
38    3    101   10_deg    -71
78    3     10   30_deg     63

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM