繁体   English   中英

在 NumPy 数组中查找最小值和最大值的索引

[英]Finding the index of the minimum and maximum values in a NumPy array

我正在使用 NBA 球员数据集和几个属性(例如身高、体重等)进行小型数据分析作业。这是数据集的一个小样本:

players = ['Aaron Gordon', 'Aaron Holiday', 'Abdel Nader', 'Al Horford', 'Al-Farouq Aminu']
years_old = [23, 22, 25, 32, 28]
height_inches = [81, 73, 78, 82, 81]
weight_pounds = [220, 185, 225, 245, 220]

我正在尝试创建一个程序来查找此数据集中最矮和最高球员的索引。 我已将这些列表转换为 NumPy 数组,并且能够成功找到最小和最高的玩家,但我不确定如何获取这些特定玩家的索引。

这是我到目前为止的代码:

np_players = np.array(players)
np_years_old = np.array(years_old)
np_height_inches = np.array(height_inches)
np_weight_pounds = np.array(weight_pounds)

def shortest_player(np_h):
  mask = np.argmin(np_h)
  idx = np.where(mask)
  return idx

def tallest_player(np_h):
  mask = np.argmax(np_h)
  idx = np.where(mask)
  return idx

这是我在运行以下行print(players[ shortest_player(np_height_meters) ] )时尝试测试这些函数时收到的错误:

TypeError Traceback (most recent call last) in () 9 return idx 10 ---> 11 print(players[tallest_player(np_height_meters)]) TypeError:列表索引必须是整数或切片,而不是元组

例如,在提供的示例数据集中,理想情况下,函数将为最短的玩家返回 1,为最高的玩家返回 3。

任何见解或建议?

如果您使用 numpy 数组,您可以简单地使用 argmax/argmin 函数:

min_h_idx = np.argmin(np_height_inches)
max_h_idx = np.argmax(np_height_inches)

和对称的权重。

这是您发布的值的简单输出:

>>> height_inches = [81, 73, 78, 82, 81]
>>> np_height_inches = np.array(height_inches)
>>> np.argmin(np_height_inches)
1
>>> np.argmax(np_height_inches)
3

笔记

在添加错误和尝试执行的行之后,传递给函数np_height_meters的参数出现问题,它没有出现在您添加的代码段中。 至于从np_height_meters更改为np_height_inches并删除仅使用argmin/argmax而没有where函数后的输出:

def shortest_player(np_h):
  idx = np.argmin(np_h)
  return idx

def tallest_player(np_h):
  idx = np.argmax(np_h)
  return idx

print(players[ shortest_player(np_height_inches) ] )

我得到的输出更改为上述内容:

Aaron Holiday

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM