gpt4 book ai didi

python - 我们可以将向量更改为 numpy 中的矩阵,向量中的元素在具有 m*n 维度的矩阵中重复

转载 作者:行者123 更新时间:2023-11-28 18:19:54 25 4
gpt4 key购买 nike

import numpy as np
import numba

@numba.vectorize('i4(i4)', target = 'parallel')
def mag(b):

return b * b

def main():

mat_a = np.full((5, 3),2,dtype=np.int32)

c = mag(mat_a)

d = np.sum(c, axis = 1)

print d

输出:[12 12 12 12 12]

但我希望输出是这样的:

[12 12 12]
[12 12 12]
[12 12 12]
[12 12 12]
[12 12 12]

明确的例子:

假设我有这样的输出:[12 13 14 15 16] 我想用 numpy 将向量中的每个元素转换成我自己的维度

[[12 12 12]
[13 13 13]
[14 14 14]
[15 15 15]
[16 16 16]]

最佳答案

如果我对问题的理解正确,您可以简单地使用 np.repeatreshape:

>>> import numpy as np

>>> arr = np.array([1,2,3,4])
>>> n = 3
>>> np.repeat(arr, n).reshape(-1, arr.size)
array([[1, 1, 1],
[2, 2, 2],
[3, 3, 3],
[4, 4, 4]])

如果结果不需要可写,您还可以使用 np.broadcast_to 和转置:

>>> n = 7
>>> np.broadcast_to(arr, (n, arr.size)).T
array([[1, 1, 1, 1, 1, 1, 1],
[2, 2, 2, 2, 2, 2, 2],
[3, 3, 3, 3, 3, 3, 3],
[4, 4, 4, 4, 4, 4, 4]])

关于python - 我们可以将向量更改为 numpy 中的矩阵,向量中的元素在具有 m*n 维度的矩阵中重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45714914/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com