[英]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 转换为 dataframeto_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.