Skip to main content
 首页 » 编程设计

python之根据数组的另一列聚合一列中的最小最大值之Python

2025年05月04日19fff_TT

如果它们具有相同的索引,我将尝试连接这些值。我正在处理矩形,所以我知道:

  • 总会有至少 2 个相同的索引。
  • 如果有超过 2 个索引,我只需要存储最大值和最小值。

基本上,

来自:

a = array([ 
       [ 1,  5], 
       [ 1,  7], 
       [ 2,  8], 
       [ 2, 10], 
       [ 2, 22], 
       [ 3, 55], 
       [ 3, 77]]) 

收件人:

b = np.array([ 
       [ 1, 5, 7], 
       [ 2, 8, 22], # [2,8,10,22] but the min is 8 and max is 22 
       [ 3, 55, 77]]) 

我尝试将其转换为列表并使用 for 循环遍历每个值,但这需要相当长的时间。

我也尝试过对数组进行排序,np.sort(a, axis=0) 并每隔一行取一次,但是由于可能有两个以上的索引,所以它失败了。

我是 numpy 的新手,所以不知道还能尝试什么。

任何和所有建议都会有所帮助,谢谢。

编辑:它的行为就像一本字典,其中键是 a[0],值是 a[1:]

如果有超过 2 个值,我只保留最小值和最大值。

请您参考如下方法:

一种使用 pandas 执行此操作的方法

import pandas as pd 
# create a dataframe with 2 columns corresponding to the columns of a 
df = pd.DataFrame({ 'indices':a[:,0],'values':a[:,1]})  
# compute min and max by indices 
df2 = df.groupby('indices').agg({'values': ['min', 'max']}).reset_index() 
# convert to numpy array 
np.asarray(df2) 
#array([[ 1,  5,  7], 
#       [ 2,  8, 22], 
#       [ 3, 55, 77]], dtype=int64)