python - 如何将向量的每个元素提升为另一个向量的每个元素的幂?

标签 python numpy array-broadcasting

我想通过从 0 到 5 的递增幂来提高向量:

import numpy as np

a = np.array([1, 2, 3]) # list of 11 components
b = np.array([0, 1, 2, 3, 4]) # power
c = np.power(a,b)
期望的结果是:
c = [[1**0, 1**1, 1**2, 1**3, 1**4], [2**0, 2**1, ...], ...]
我不断收到此错误:
ValueError: operands could not be broadcast together with shapes (3,) (5,)

最佳答案

一种解决方案是为数组添加一个新维度 a

c = a[:,None]**b

# Using broadcasting : 
# (3,1)**(4,) --> (3,4)
#
#     [[1],
# c =  [2], ** [0,1,2,3,4]
#      [3]]
有关更多信息,请查看 numpy broadcasting documentation

关于python - 如何将向量的每个元素提升为另一个向量的每个元素的幂?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66242475/

相关文章:

Python 将 N 维体积划分为统一的子体积

python - 给定条件的矩阵上的 Numpy 高级索引

python - numpy.einsum 中的省略号广播

python:迭代列表或异步生成器

python - 替换字符串的各个字符元素

python - 检查 2d 点是否在曲线上

python - Pandas 应用类型错误 : 'float' object is not subscriptable

python - 为什么这不分配一个副本

python - 使用 int dtype 的 numpy 数组计算出错(它无法在需要时自动将 dtype 转换为 64 位)

python - 有没有更好的方法来广播数组?