0

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

1
  • Your subject line talks about 'insertion', while question asks about 'concatenate'. Have you considered making np.zeros((n.m,2)) array, and assigning the arrays to it? That's a kind of insertion. Commented Mar 16, 2024 at 18:27

1 Answer 1

2

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"))
Sign up to request clarification or add additional context in comments.

1 Comment

In a recent answer to a similar question, I found that the best (fastest) use of broadcasting was to assign the arrays to a predefined zeros array. stackoverflow.com/a/78110268/901925

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.