简体   繁体   中英

With numpy, what's the fastest way to generate an array from -n to n, excluding 0, being `n` an integer?

With numpy, what's the fastest way to generate an array from -n to n, excluding 0, being n an integer?

Follows one solution, but I am not sure this is the fastest:

n = 100000
np.concatenate((np.arange(-n, 0), np.arange(1, n+1)))

An alternative approach is to create the range -n to n-1. Then add 1 to the elements from zero.

def non_zero_range(n):
    # The 2nd argument to np.arange is exclusive so it should be n and not n-1
    a=np.arange(-n,n)
    a[n:]+=1
    return a

n=1000000
%timeit np.concatenate((np.arange(-n,0), np.arange(1,n+1)))
# 4.28 ms ± 9.46 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

%timeit non_zero_range(n)
# 2.84 ms ± 13.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

I think the reduced response time is due to only creating one array, not three as in the concatenate approach.

Edit

Thanks, everyone. I edited my post and updated new test time.

Interesting problem.

Experiment

I did it in my jupyter-notebook. All of them used numpy API. You can conduct the experiment of the following code by yourself.

About time measurement in jupyter-notebook, please see: Simple way to measure cell execution time in ipython notebook

Original np.concatenate

%%timeit 
n = 100000
t = np.concatenate((np.arange(-n, 0), np.arange(1, n+1)))

#175 µs ± 2.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Sol 1. np.delete

%%timeit 
n = 100000
a = np.arange(-n, n+1)
b = np.delete(a, n)

# 179 µs ± 5.66 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Sol 2. List comprehension + np.arrary

%%timeit
c = np.array([x for x in range(-n, n+1) if x != 0])

# 16.6 ms ± 693 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

Conclusion

There's no big difference between original and solution 1, but solution 2 is the worst among the three. I'm looking for faster solutions, too.

Reference

For those who are:

interested in initialize and fill an numpy array

get confused of is vs ==

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM