Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Elementwise insertion of array into array using numpy

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[[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_arrays creates views of (n_years, n_months), (n_years, n_months)
  • np.dstack concatenates 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"))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading