gpt4 book ai didi

python - 根据条件在python中具有不同值范围的三个列表中选择最佳索引

转载 作者:太空宇宙 更新时间:2023-11-04 08:28:09 26 4
gpt4 key购买 nike

我有一个包含三个键的字典,它由一个长度相同的列表组成。例如,键“a”有一个长度为 5 的列表,包含范围为 0 到 6000 的值。类似地,键“b”的长度为 5,其值范围为 0 到 1.0。最后,具有相同长度的键 'c' 的值范围从 (1x1) 到 (2000x2000)。

我必须在 0 到 4 之间选择一个索引,条件是“a”的值不能低于 200。“b”的值不能低于 0.95。然后,在满足这两个条件的指标中选择最高值的'c'。

一个虚拟数据如下,

  index     a          b           c
0 600 0.99 (100x105)
1 150 1.0 (50x40)
2 820 0.75 (500x480)
3 500 0.96 (200x190)
4 400 0.97 (120x110)

在这里,根据这两个条件,我可以将索引筛选为 0、3 和 4。在这三个中,'c' 的最大值是索引 3。所以答案是 3 500 0.96 (200x190 )

我如何以最有效的方式选择它?我想我可能需要使用 Pandas 。我怎么能用 Pandas 做呢?另外,如何以最 pythonic 的方式做到这一点?

我对编码比较陌生。我很难弄明白。

编辑:字典的代码片段

{
'a' : [600, 150, 820, 500, 400]
'b' : [0.99, 1.0, 0.75, 0.96, 0.97]
'c' : [(100,105), (50,40), (500,480), (200,190), (120,110)]
}

最佳答案

这对于 numpy 来说相对简单,尽管 c 列的格式有点奇怪提供了一个有趣的转折。

import numpy as np

d = {
'a' : [600, 150, 820, 500, 400],
'b' : [0.99, 1.0, 0.75, 0.96, 0.97],
'c' : [(100,105), (50,40), (500,480), (200,190), (120,110)]
}

# Load as numpy arrays.
d_np = {key: np.array(value) for key, value in d.items()}

# Create logical mask based on given requirements
mask = np.logical_and(d_np['a'] > 200, d_np['b'] > 0.95)

# Multiply 'c' along dimension 1
c_product = np.prod(d_np['c'], axis=1)

# Get index of maximum value. Note that this index is relative to masked array.
max_index_masked = np.argmax(c_product[mask])

# Get original 'c' value. Need to mask the array so that our indexing works.
max_value = d_np['c'][mask][max_index_masked]

# Get index relative to unmasked array
index = np.arange(d_np['c'].shape[0])[mask][max_index_masked]
print(index)

关于python - 根据条件在python中具有不同值范围的三个列表中选择最佳索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55155491/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com