簡體   English   中英

遍歷二維 numpy 數組以找到對應的最大值

[英]Iterate over 2D numpy array to find corresponding maximum values

我有一組數據:

interactions=np.array([[0,1], [0,2], [0,3], [1,2], [1, 4], [2, 1], [2,5], [2,7]])

我需要遍歷第一列中的每個值,在第二列中找到相應的最大值,然后存儲在一個新數組中(或從該數組中刪除其他值)。 對於此示例,最終的 output 將因此為:

interactions=[[0, 3], [1, 4], [2,7]]

我已經設法編寫了一段代碼,它將為特定的列值執行此操作,但無法弄清楚如何將它變成一個循環來執行整個數組:

創建一個數組來存儲值:

p_gamma=np.amax(interactions[:,0])
zfinal=np.zeros([np.int(p_gamma)+1, 2])

找到每個列值的最大值(這是我需要幫助的地方:):

counter=0
interactions=interactions[interactions[:,0] ==counter]
maxval=np.amax(interactions[:, 1])
interactions=interactions[interactions[:, 1] == maxval]
zfinal[0,:]=interactions

提前感謝您提供的任何幫助!!!

numpy方法是:

i = np.flatnonzero(np.diff(interactions[:, 0])) + 1   # finding indices where first column changes
np.maximum.reduceat(interactions, np.r_[0, i])        # taking maximum values between those indices

array([[0, 3],
       [1, 4],
       [2, 7]], dtype=int32)

使用 pandas groupby 第一列0並取最大值並轉換回 numpy 數組:

import pandas as pd
pd.DataFrame(interactions).groupby(0).max().reset_index().to_numpy()

output:

[[0 3]
 [1 4]
 [2 7]]

說明

  • pd.DataFrame(interactions) : 從 numpy 數組創建一個數據框
  • groupby(0) :按第一列分組數據
  • max() : 查找每組中第二列的最大值
  • reset_index() : 將 groupby object 轉換為 dataframe
  • to_numpy() : 將 dataframe 轉換為 numpy 數組

這是一種可能的單行解決方案,無需使用任何額外的庫:

result = list(zip(np.unique(interactions[:,0]),
                  map(max, np.split(interactions[:,1], 
                                    np.unique(interactions[:,0], 
                                              return_index=True)[1][1:]))))

Output:

[(0, 3), (1, 4), (2, 7)]

暫無
暫無

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

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