【问题标题】:numpy vectorized assignment of sequences [duplicate]序列的numpy向量化分配[重复]
【发布时间】:2017-04-04 06:29:57
【问题描述】:

numpy like in this discussion 中的序列是否有元素的矢量化分配?

例如:

xx = np.array([1,2], dtype=object)
expanded = np.arange(xx, xx+2)

而不是循环:

xx = np.array([1,2], dtype=object)
expanded = np.array([np.arange(x, x+2) for x in xx]).flatten()

这将用于将标量启发式映射到确定它的矩阵中的相邻单元格(例如,与@987654325 有峰值重叠的单元格的范围 @操作)。

【问题讨论】:

标签: python arrays numpy vectorization


【解决方案1】:

像这样?

>>> xx = np.array([3,8,19])
>>> (xx[:,None]+np.arange(2)[None,:]).flatten()
array([ 3,  4,  8,  9, 19, 20])

xx[:,None] 操作将长度为 n 的向量转换为 nx1 矩阵,np.arange(2)[None,:]) 操作创建包含[0., 1.] 的长度为 1x2 的矩阵。使用array broadcasting 相加得到一个 nx2 矩阵,然后将其展平为长度为 2n 的向量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-30
    • 1970-01-01
    • 1970-01-01
    • 2019-05-19
    • 2014-03-13
    • 2021-09-25
    • 2017-03-28
    相关资源
    最近更新 更多