Skip to content

商务合作:vTikTok


公众号:



Numpy是Python中用于科学计算的一个重要的库,它提供了高效的多维数组对象和各种用于数组操作的函数。下面是Numpy的一些基础用法:

  1. 导入Numpy库

在使用Numpy之前,需要先导入Numpy库:

python
import numpy as np
import numpy as np
  1. 创建数组

可以使用Numpy的array()函数来创建数组,例如:

python
a = np.array([1, 2, 3])
b = np.array([[1, 2, 3], [4, 5, 6]])
a = np.array([1, 2, 3])
b = np.array([[1, 2, 3], [4, 5, 6]])

其中,a是一个一维数组,b是一个二维数组。

  1. 数组属性

可以使用shape属性来获取数组的形状,例如:

python
print(a.shape)  # 输出 (3,)
print(b.shape)  # 输出 (2, 3)
print(a.shape)  # 输出 (3,)
print(b.shape)  # 输出 (2, 3)

可以使用dtype属性来获取数组的数据类型,例如:

python
print(a.dtype)  # 输出 int64
print(b.dtype)  # 输出 int64
print(a.dtype)  # 输出 int64
print(b.dtype)  # 输出 int64
  1. 数组运算

可以对数组进行各种运算,例如:

python
c = a + b
d = a * b
e = np.dot(a, b.T)
c = a + b
d = a * b
e = np.dot(a, b.T)

其中,cd分别是ab的对应元素相加和相乘的结果,eab的矩阵乘积。

  1. 数组索引和切片

可以使用索引和切片来访问数组中的元素,例如:

python
print(a[0])     # 输出 1
print(b[1, 2])  # 输出 6
print(b[:, 1])  # 输出 [2 5]
print(a[0])     # 输出 1
print(b[1, 2])  # 输出 6
print(b[:, 1])  # 输出 [2 5]

其中,a[0]表示访问a数组中的第一个元素,b[1, 2]表示访问b数组中第二行第三列的元素,b[:, 1]表示访问b数组中所有行的第二列元素。

  1. 数组的其他操作

可以使用reshape()函数来改变数组的形状,例如:

python
f = np.arange(12).reshape(3, 4)
f = np.arange(12).reshape(3, 4)

其中,f是一个3行4列的二维数组。

可以使用transpose()函数来转置数组,例如:

python
g = f.transpose()
g = f.transpose()

其中,gf的转置。

可以使用sum()函数来计算数组中所有元素的和,例如:

python
h = f.sum()
h = f.sum()

其中,hf中所有元素的和。

以上是Numpy的一些基础用法,更多详细的用法可以参考Numpy的官方文档。