gpt4 book ai didi

python - 寻找最大正值或最小负值的向量化版本

转载 作者:太空宇宙 更新时间:2023-11-03 15:06:52 24 4
gpt4 key购买 nike

假设我有一个名为 purity_list 的 pandas DataFrame,如下所示:

In[]: purity_list
Out[]:
48 49 50
2 0.1 0.9 0.3
A 0.2 -0.5 -0.6
4 0.3 0.8 0.9

我想将其与另一个 numpy 数组进行比较并获取最大 +ve 值,如果没有 +ve 值,我想要最低的 -ve 值。

假设我将其与名为 purities 的 numpy 数组进行比较,如下所示:

In[]: purities
Out[]:
array([-0.2, 0.2, -0.8])

我现在拥有的最接近的矢量化代码是:

purity_list = np.where(np.absolute(purity_list) > np.absolute(purities), 
purity_list, purities)

当我运行该代码时,我将得到以下结果:

In[]: purity_list
Out[]:
48 49 50
2 -0.2 0.9 -0.8
A -0.2 -0.5 -0.8
4 0.3 0.8 0.9

我真正想要的是稍微不同的东西。我这里有非向量化逻辑:

for i, v1 in enumerate(purity_list):
for j, v2 in enumerate(v1):
if v2 > 0 or purities[j] > 0:
purity_list.iloc[i, j] = np.max(purity_list.iloc[i, j], purities[j])
else:
purity_list.iloc[i, j] = np.min(purity_list.iloc[i, j], purities[j])

结果将是:

In[]: purity_list
Out[]:
48 49 50
2 0.1 0.9 0.3
A 0.2 0.2 -0.8
4 0.3 0.8 0.9

这就是我想要的结果。我重复这个语句超过 100,000 次,而且我的数组非常大,所以我需要一个矢量化版本。性能是这里的关键。

最佳答案

您的 np.where 版本中的逻辑不太正确。考虑当负值的幅度大于与之比较的正值时会发生什么。不过,工具的选择是合理的。因此,您需要做的就是纠正条件以更好地符合您的目标:

np.where((purity_list < 0) & (purities < 0),
np.where(purity_list < purities, purity_list, purities),
np.where(purity_list > purities, purity_list, purities))
Out[42]:
array([[ 0.1, 0.9, 0.3],
[ 0.2, 0.2, -0.8],
[ 0.3, 0.8, 0.9]])

如果嵌套 np.where 感觉很愚蠢,可以组合逻辑:

np.where(((purity_list < 0) & (purities < 0) & (purity_list < purities))
|(((purity_list > 0) | (purities > 0)) & (purity_list > purities)),
purity_list, purities)
Out[43]:
array([[ 0.1, 0.9, 0.3],
[ 0.2, 0.2, -0.8],
[ 0.3, 0.8, 0.9]])

虽然我发现第一种方式更清晰。

关于python - 寻找最大正值或最小负值的向量化版本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44578733/

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