There is another NumPy solution with only slightly worse performance than the one posted by @AMC, but with the convenience that it is a single expression and doesn't need to be wrapped in a function to be used inline:
>>> n = 10
>>> np.eye(1, n + 1, 0, dtype=int)[0]
array([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
It's also easy to create other one-hot vectors of the same length by changing the third argument:
>> np.eye(1, n + 1, 4, dtype=int)[0]
array([0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0])
Here's how the performance compares to @AMC's func_2
above (same arr_size = 100000000
):
def func_8(n, k=0):
return np.eye(1, n + 1, k, dtype=int)[0]
>>> %timeit func_2(arr_size)
16.4 µs ± 111 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
>>> %timeit func_8(arr_size)
19 µs ± 113 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
list
, by the way, because it will override the built-in namelist