Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
175 views
in Technique[技术] by (71.8m points)

numpy - How to generate vector in Python

There is a random 1D array m_0

np.array([0, 1, 2])

I need to generate two 1D arrays:

np.array([0, 1, 2, 0, 1, 2, 0, 1, 2])
np.array([0, 0, 0, 1, 1, 1, 2, 2, 2])

Is there faster way to do it than this one:

import numpy as np
import time
N = 3
m_0 = np.arange(N)

t = time.time()
m_1 = np.tile(m_0, N)
m_2 = np.repeat(m_0, N)
t = time.time() - t

Size of m_0 is 10**3

question from:https://stackoverflow.com/questions/65642057/how-to-generate-vector-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could use itertools.product to form the Cartesian product of m_0 with itself, then take the result apart again to get your two arrays.

import numpy as np
from itertools import product

N = 3
m_0 = np.arange(N)

m_2, m_1 = map(np.array, zip(*product(m_0, m_0)))

# m_1 is now array([0, 1, 2, 0, 1, 2, 0, 1, 2])
# m_2 is now array([0, 0, 0, 1, 1, 1, 2, 2, 2])

However, for large N this is probably quite a bit less performant than your solution, as it probably can't use many of NumPy's SIMD optimizations.

For alternatives and comparisons, you'll probably want to look at the answers to Cartesian product of x and y array points into single array of 2D points.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...