[英]Is there a more elegant way of creating these numpy arrays?
我觉得我创建了太多数组并浪费资源,所以我正在寻找一种更清洁、更有效的方法来解决以下问题:
假设我们有一个振荡图,并且我们知道最小值 ( min_x˛
) 和最大值 ( max_x
) 的位置。 我们选择一个参考点ref_point
(下图中的 2.35 左右),最接近的极值(图中的 2.25 和 2.45)我们分配 1 * PI,给第二个最接近的极值我们分配值 2 * PI,并且很快。 这样我们就可以得到图中下方的图(请注意,这些值被 -4*PI 抵消了,但这暂时无关紧要)。
这是我的解决方案:
import numpy as np
def min_max(ref_point, min_x, max_x):
# finding the maximum and minimum values which are smaller than reference point
neg_max_freq = np.array([a for a in (ref_point - max_x) if a < 0])
neg_min_freq = np.array([b for b in (ref_point - min_x) if b < 0])
# joining them together and flipping order
neg_freq = sorted(np.append(neg_max_freq, neg_min_freq), reverse=True)
# finding the maximum and minimum values which are greater than reference point
pos_max_freq = np.array([c for c in (ref_point - max_x) if c > 0])
pos_min_freq = np.array([d for d in (ref_point - min_x) if d > 0])
#joining them together
pos_freq = sorted(np.append(pos_min_freq, pos_max_freq))
pos_values = np.array([np.pi * (i+1) for i in range(len(pos_freq))])
neg_values = np.array([np.pi * (i+1) for i in range(len(neg_freq))])
# joining the values for the lower graph on the picture
x_s = np.append(pos_freq, neg_freq)
y_s = np.append(pos_values, neg_values)
return x_s, y_s
用法示例:
>>> min_x = np.arange(np.pi/2, 4.5*np.pi, np.pi)
>>> max_x = np.arange(0, 4*np.pi, np.pi)
>>> x, y = min_max(0, min_x, max_x)
>>> x
[ -1.57079633 -3.14159265 -4.71238898 -6.28318531 -7.85398163
-9.42477796 -10.99557429]
>>> y
[ 3.14159265 6.28318531 9.42477796 12.56637061 15.70796327 18.84955592
21.99114858]
是否有另一种更有效的方法来实现相同的结果?
在这里,我将如何更改min_max
代码而不编写如此多的临时变量并避免列表理解:
def min_max(ref_point, min_x, max_x):
max_freq = ref_point - max_x
min_freq = ref_point - min_x
# Faster sort
neg_freq = np.sort(np.append(max_freq[max_freq<0], min_freq[min_freq<0]))[::-1]
pos_freq = np.sort(np.append(max_freq[max_freq>0], min_freq[min_freq>0]))
pos_values = np.pi * np.arange(1, len(pos_freq)+1)
neg_values = np.pi * np.arange(1, len(neg_freq)+1)
x_s = np.append(pos_freq, neg_freq)
y_s = np.append(pos_values, neg_values)
return x_s, y_s
关于排序性能,我用大小为 100 万的随机数组进行了测试,结果如下:
a = np.random.randint(0, 1000, 1_000_000)
%timeit sorted(a, reverse=True)
522 ms ± 29.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit np.sort(a)[::-1]
55.2 ms ± 958 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
numpy 比 vanilla python 快 9.5 倍。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.