Let’s say I have an array of years created like
years = np.arange(2024,2051,1)
And I have an array of months created like
months = np.arange(1,13,1)
What is the most pythonic way of arriving at an elementwise concatenation such that the end result is
[[2024,1],[2024,2],[2024,3]…[2024,12],
[2025,1],[2025,2],[2025,3]…[2025,12],
…
]
?
Thanks
>Solution :
I’d say the most pythonic is:
out = [[year, month] for year in years for month in months]
There is also itertools.product, but it will give you a list of tuples.
from itertools import product
out = list(product(years, months))
If you want to be full numpy, you can take advantage of broadcasting.
import numpy as np
out = np.dstack(np.broadcast_arrays(*np.ix_(years, months)))
np.ix_reshapes the input arrays to be(n_years, 1), (1, n_months)np.broadcast_arrayscreates views of(n_years, n_months), (n_years, n_months)np.dstackconcatenates the above such that you get a(n_years, n_months, 2)array.
Edit:
I just realised that np.ix_ + np.broadcast_arrays is more or less a np.meshgrid:
out = np.dstack(np.meshgrid(years, months, indexing="ij"))