使用 numpy 将数组按元素插入数组

问题描述 投票:0回答:1

假设我创建了一系列年份,例如

years = np.arange(2024,2051,1)

我创建了一系列月份

months = np.arange(1,13,1)

达到元素级联的最 Pythonic 方法是什么,最终结果是

[[2024,1],[2024,2],[2024,3]...[2024,12], [2025,1],[2025,2],[2025,3]...[2025,12], ... ]

谢谢

numpy
1个回答
0
投票

我想说最Pythonic的是:

out = [[year, month] for year in years for month in months]

还有

itertools.product
,但它会给你一个元组列表。

from itertools import product
out = list(product(years, months))

如果你想完全numpy,你可以利用广播。

import numpy as np
out = np.dstack(np.broadcast_arrays(*np.ix_(years, months)))
  • np.ix_
    将输入数组重塑为
    (n_years, 1), (1, n_months)
  • np.broadcast_arrays
    创建
    (n_years, n_months), (n_years, n_months)
  • 的视图
  • np.dstack
    连接上面的内容,得到一个
    (n_years, n_months, 2)
    数组。
© www.soinside.com 2019 - 2024. All rights reserved.