gpt4 book ai didi

python - Numpy 查找( map 或点)

转载 作者:太空狗 更新时间:2023-10-29 21:27:27 26 4
gpt4 key购买 nike

我有一个大的 numpy 数组:

array([[32, 32, 99,  9, 45],  # A
[99, 45, 9, 45, 32],
[45, 45, 99, 99, 32],
[ 9, 9, 32, 45, 99]])

以及按特定顺序排列的大型唯一值数组:

array([ 99, 32, 45, 9])       # B

我怎样才能快速(没有 python 字典,没有 A 的副本,没有 python 循环)替换 A 中的值从而成为 B 中值的指标?:

array([[1, 1, 0, 3, 2],
[0, 2, 3, 2, 1],
[2, 2, 0, 0, 1],
[3, 3, 1, 2, 0]])

我觉得自己很蠢,因为我无法凭空想到这个,也无法在文档中找到它。轻松积分!

最佳答案

给你

A = array([[32, 32, 99,  9, 45],  # A
[99, 45, 9, 45, 32],
[45, 45, 99, 99, 32],
[ 9, 9, 32, 45, 99]])

B = array([ 99, 32, 45, 9])

ii = np.argsort(B)
C = np.digitize(A.reshape(-1,),np.sort(B)) - 1

最初我建议:

D = np.choose(C,ii).reshape(A.shape)

但我意识到,当您使用更大的阵列时,这会带来局限性。相反,借用@unutbu 的聪明回复:

D = np.argsort(B)[C].reshape(A.shape)

或者单线

np.argsort(B)[np.digitize(A.reshape(-1,),np.sort(B)) - 1].reshape(A.shape)

我发现它比@unutbu 的代码更快或更慢,具体取决于所考虑的数组大小和唯一值的数量。

关于python - Numpy 查找( map 或点),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5036816/

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