gpt4 book ai didi

python - 区别 np.where 和这个解决方法?

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

在问题“Efficiently create a density plot for high-density regions, points for sparse regions”中,要求用 NaN 替换低密度区域。接受的答案中的相关代码如下:

hh, locx, locy = scipy.histogram2d(xdat, ydat, range=xyrange, bins=bins)
posx = np.digitize(xdat, locx)
posy = np.digitize(ydat, locy)

#select points within the histogram
ind = (posx > 0) & (posx <= bins[0]) & (posy > 0) & (posy <= bins[1])
hhsub = hh[posx[ind] - 1, posy[ind] - 1] # values of the histogram where the points are
xdat1 = xdat[ind][hhsub < thresh] # low density points
ydat1 = ydat[ind][hhsub < thresh]
hh[hh < thresh] = np.nan # fill the areas with low density by NaNs

我发现了类似的东西

hh = np.where(hh > thresh, hh, np.nan)

也在工作。两者在执行结果方面有何不同?

最佳答案

高级索引(即您的原始方法)在结果相同的情况下更有效!

我将这两个选项与以下代码进行了比较:

import numpy as np
import time

t1 = time.time()
for i in xrange(1000):
a = np.random.rand(10)
a[a>0.5] = np.nan
t2 = time.time()
print 'adv. idx.: ',t2-t1

t1 = time.time()
for i in xrange(1000):
a = np.random.rand(10)
a = np.where(a>0.5,np.nan,a)
t2 = time.time()
print 'np.where: ',t2-t1

结果很明显:

adv. idx.:  0.00600004196167
np.where: 0.0339999198914

np.where 明显变慢了!结果相同。但是,这无法通过 == 比较进行验证,因为 np.nan == np.nan 会产生 False

关于python - 区别 np.where 和这个解决方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28210470/

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