使用Numpy设置第一个数组元素,使其逐元素对应第二个数组中的幂


要将第一个数组的元素逐元素地提高到第二个数组的幂,请在Python中使用**numpy.power()**方法。这里,第一个参数是底数,第二个参数是指数。

将x1中的每个底数提高到x2中位置对应的幂。x1和x2必须可广播到相同的形状。整数类型提高到负整数幂将引发ValueError。负值提高到非整数值将返回nan。要获得复数结果,请将输入转换为复数,或指定dtype为复数。

out是存储结果的位置。如果提供,它必须具有输入广播到的形状。如果没有提供或为None,则返回一个新分配的数组。元组(仅可能作为关键字参数)的长度必须等于输出的数量。

步骤

首先,导入所需的库:

import numpy as np

创建一个数组:

arr = np.array([5, 10, 25, 30, 40, 50])

显示数组:

print("Array...
", arr)

获取数组的类型:

print("
Our Array type...
", arr.dtype)

获取数组的维度:

print("
Our Array Dimension...
",arr.ndim)

获取数组的形状:

print("
Our Array Shape...
",arr.shape)

设置指数:

p = [2, 3, 2, 3, 2, 3]

要将第一个数组元素逐元素地提高到第二个数组的幂,请使用numpy.power()方法。这里,第一个参数是底数,第二个参数是指数:

print("
Result...
",np.power(arr, p))

示例

import numpy as np

# Create an array
arr = np.array([5, 10, 25, 30, 40, 50])

# Display the array
print("Array...
", arr) # Get the type of the array print("
Our Array type...
", arr.dtype) # Get the dimensions of the Array print("
Our Array Dimension...
",arr.ndim) # Get the shape of the Array print("
Our Array Shape...
",arr.shape) # Set the exponent p = [2, 3, 2, 3, 2, 3] # To set the first array elements raised to powers from second array, element-wise, use the numpy.power() method in Python # Here, the 1st parameter is the base and the 2nd exponents print("
Result...
",np.power(arr, p))

输出

Array...
[ 5 10 25 30 40 50]

Our Array type...
int64

Our Array Dimension...
1

Our Array Shape...
(6,)

Result...
[ 25 1000 625 27000 1600 125000]

更新于:2022年2月7日

570 次浏览

启动你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.