创建和保存NumPy ndarray
import time
import numpy as np
x = np.random.random(100000000)
start = time.time()
sum(x) / len(x)
print(time.time() - start)
start = time.time()
np.mean(x)
print(time.time() - start)
0.11332511901855469
# We import NumPy into Python
import numpy as np
# We create a 1D ndarray that contains only integers
x = np.array([1, 2, 3, 4, 5])
# Let's print the ndarray we just created using the print() command
print('x = ', x)
x = [1 2 3 4 5]
x = np.array([1,2,3,4,5])
print()
print('x = ', x)
print()
print('x has dimension:',x.shape)
print('x is an object of type:',type(x))
print('The elements in x are of type:', x.dtype)
x = [1 2 3 4 5]
x has dimension: (5,)
x is an object of type: <class 'numpy.ndarray'>
The elements in x are of type: int64
可以看出,shape 属性返回了元组 (5,),告诉我们 x 的秩为 1(即 x 只有一个维度),并且有 5 个元素。type() 函数告诉我们 x 的确是 NumPy ndarray。最后,.dtype 属性告诉我们 x 的元素作为有符号 64 位整数存储在内存中。NumPy 的另一个重要优势是能够处理的数据类型比 Python 列表要多。你可以在以下链接中查看 NumPy 支持的所有不同数据类型:
x = np.array(['Hello', 'World'])
# We print x
print()
print('x = ', x)
print()
# We print information about x
print('x has dimensions:', x.shape)
print('x is an object of type:', type(x))
print('The elements in x are of type:', x.dtype)
x = ['Hello' 'World']
x has dimensions: (2,)
x is an object of type: <class 'numpy.ndarray'>
The elements in x are of type: <U5
可以看出,shape 属性告诉我们 x 现在只有 2 个元素,虽然 x 现在存储的是字符串,但是 type() 函数告诉我们 x 依然像之前一样是 ndarray。但是,.dtype 属性告诉我们 x 中的元素作为具有 5 个字符的 Unicode 字符串存储在内存中。
请务必注意,Python 列表和 ndarray 之间的最大区别是:与 Python 列表不同的是,ndarray 的所有元素都必须类型相同。因此,虽然我们可以同时使用整数和字符串创建 Python 列表,但是无法在 ndarray 中同时使用这两种类型。如果向 np.array() 函数提供同时具有整数和字符串的 Python 列表,NumPy 会将所有元素解析为字符串。我们可以在下面的示例中见到这种情况:
# We create a rank 1 ndarray from a Python list that contains integers and strings
x = np.array([1, 2, 'World'])
# We print the ndarray
print()
print('x = ', x)
print()
# We print information about x
print('x has dimensions:', x.shape)
print('x is an object of type:', type(x))
print('The elements in x are of type:', x.dtype)
x = ['1' '2' 'World']
x has dimensions: (3,)
x is an object of type: <class 'numpy.ndarray'>
The elements in x are of type: <U21
可以看出,虽然 Python 列表具有不同的数据类型,但是 x 中的元素类型都一样,即具有 21 个字符的 Unicode 字符串。在 NumPy 简介的剩余部分,我们将不使用存储字符串的 ndarray,但是请注意,ndarray 也可以存储字符串。
现在看看如何利用嵌套 Python 列表创建秩为 2 的 ndarray。
# We create a rank 2 ndarray that only contains integers
Y = np.array([[1,2,3],[4,5,6],[7,8,9], [10,11,12]])
# We print Y
print()
print('Y = \n', Y)
print()
# We print information about Y
print('Y has dimensions:', Y.shape)
print('Y has a total of', Y.size, 'elements')
print('Y is an object of type:', type(Y))
print('The elements in Y are of type:', Y.dtype)
Y =
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]
Y has dimensions: (4, 3)
Y has a total of 12 elements
Y is an object of type: <class 'numpy.ndarray'>
The elements in Y are of type: int64
可以看出,现在 shape 属性返回元组 (4,3),告诉我们 Y 的秩为 2,有 4 行 3 列。.size 属性告诉我们 Y 共有 12 个元素。
注意,当 NumPy 创建 ndarray 时,它会自动根据用于创建 ndarray 的元素的类型为其分配 dtype。到目前为止,我们只创建了包含整数和字符串的 ndarray。我们发现,当我们创建只有整数的 ndarray 时,NumPy 将自动为其元素分配 dtype int64。我们来看看当我们创建具有浮点数和整数的 ndarray 时,会发生什么。
# We create a rank 1 ndarray that contains integers
x = np.array([1,2,3])
# We create a rank 1 ndarray that contains floats
y = np.array([1.0,2.0,3.0])
# We create a rank 1 ndarray that contains integers and floats
z = np.array([1, 2.5, 4])
# We print the dtype of each ndarray
print('The elements in x are of type:', x.dtype)
print('The elements in y are of type:', y.dtype)
print('The elements in z are of type:', z.dtype)
The elements in x are of type: int64
The elements in y are of type: float64
The elements in z are of type: float64
可以看出,当我们创建只有浮点数的 ndarray 时,NumPy 将元素当做* 64 位浮点数 (float64)* 存储在内存中。但是,当我们创建同时包含浮点数和整数的 ndarray 时,就像上面的 z ndarray,NumPy 也会为其元素分配 float64 dtype。这叫做向上转型。因为 ndarray 的所有元素都必须类型相同,因此在这种情况下,NumPy 将 z 中的整数向上转型为浮点数,避免在进行数学计算时丢失精度。
虽然 NumPy 自动为 ndarray 选择 dtype,但是 NumPy 也允许你指定要为 ndarray 的元素分配的特定 dtype。当你在 np.array() 函数中创建 ndarray 时,可以使用关键字 dtype 指定 dtype。我们来看一个示例:
# We create a rank 1 ndarray of floats but set the dtype to int64
x = np.array([1.5, 2.2, 3.7, 4.0, 5.9], dtype = np.int64)
# We print x
print()
print('x = ', x)
print()
# We print the dtype x
print('The elements in x are of type:', x.dtype)
x = [1 2 3 4 5]
The elements in x are of type: int64
可以看出,虽然用浮点数创建了 ndarray,但是通过将 dtype 指定为 int64,NumPy 通过去除小数将浮点数转换成了整数。如果你不希望 NumPy 意外地选择错误的数据类型,或者你只希望达到一定的计算精度,从而节省内存,则指定 ndarray 的数据类型很有用。
创建 ndarray 后,你可能需要将其保存到文件中,以便以后读取该文件或供另一个程序使用。NumPy 提供了一种将数组保存到文件中以供日后使用的方式。我们来看看操作方式。
# We create a rank 1 ndarray
x = np.array([1, 2, 3, 4, 5])
# We save x into the current directory as
np.save('my_array', x)
# We load the saved array from our current directory into variable y
y = np.load('my_array.npy')
# We print y
print()
print('y = ', y)
print()
# We print information about the ndarray we loaded
print('y is an object of type:', type(y))
print('The elements in y are of type:', y.dtype)
y = [1 2 3 4 5]
y is an object of type: <class 'numpy.ndarray'>
The elements in y are of type: int64
从文件中加载数组时,确保包含文件名和扩展名 .npy,否则将出错。
使用内置函数创建ndarry
我们先创建一个具有指定形状的 ndarray,其中的元素全是 0。为此,我们可以使用 np.zeros() 函数。函数 np.zeros(shape) 会创建一个全是 0 并且为给定形状的 ndarray。因此,例如如果你想创建一个秩为 2 的数组,其中包含 3 行和 4 列,你将以 (行, 列) 的形式将该形状传递给函数,如以下示例所示:
# We create a 3 x 4 ndarray full of zeros.
X = np.zeros((3,4))
# We print X
print()
print('X = \n', X)
print()
# We print information about X
print('X has dimensions:', X.shape)
print('X is an object of type:', type(X))
print('The elements in X are of type:', X.dtype)
X =
[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]
X has dimensions: (3, 4)
X is an object of type: <class 'numpy.ndarray'>
The elements in X are of type: float64
可以看出,np.zeros() 函数默认地创建一个 dtype 为 float64 的数组。你可以使用关键字 dtype 更改数据类型。
同样,我们可以创建一个具有指定形状的 ndarray,其中的元素全是 1。
为此,我们可以使用 np.ones() 函数。和 np.zeros() 函数一样,np.ones() 函数会用一个参数来指定你要创建的 ndarray 的形状。
我们来看一个示例:
# We create a 3 x 2 ndarray full of ones.
X = np.ones((3,2))
# We print X
print()
print('X = \n', X)
print()
# We print information about X
print('X has dimensions:', X.shape)
print('X is an object of type:', type(X))
print('The elements in X are of type:', X.dtype)
X =
[[1. 1.]
[1. 1.]
[1. 1.]]
X has dimensions: (3, 2)
X is an object of type: <class 'numpy.ndarray'>
The elements in X are of type: float64
们还可以创建一个具有指定形状的 ndarray,其中的元素全是我们想指定的任何数字。为此,我们可以使用 np.full() 函数。np.full(shape, constant value) 函数有两个参数。第一个参数是你要创建的 ndarray 的形状,第二个参数是你要向数组中填充的常数值。我们来看一个示例:
# We create a 2 x 3 ndarray full of fives.
X = np.full((2,3), 5)
# We print X
print()
print('X = \n', X)
print()
# We print information about X
print('X has dimensions:', X.shape)
print('X is an object of type:', type(X))
print('The elements in X are of type:', X.dtype)
X =
[[5 5 5]
[5 5 5]]
X has dimensions: (2, 3)
X is an object of type: <class 'numpy.ndarray'>
The elements in X are of type: int64
稍后你将发现,线性代数中的基本数组是单位矩阵。单位矩阵是主对角线上全是 1,其他位置全是 0 的方形矩阵。函数 np.eye(N) 会创建一个对应于单位矩阵的方形 N x N ndarray。因为所有单位矩阵都是方形,因此,np.eye() 函数仅接受一个整数作为参数。我们来看一个示例:
# We create a 5 x 5 Identity matrix.
X = np.eye(5)
print()
print('X = \n', X)
print()
print('X has dimensions:', X.shape)
print('X is an object of type:', type(X))
print('The elements in X are of type:', X.dtype)
X =
[[1. 0. 0. 0. 0.]
[0. 1. 0. 0. 0.]
[0. 0. 1. 0. 0.]
[0. 0. 0. 1. 0.]
[0. 0. 0. 0. 1.]]
X has dimensions: (5, 5)
X is an object of type: <class 'numpy.ndarray'>
The elements in X are of type: float64
可以看出,np.eye() 函数也默认地创建一个 dtype 为 float64 的数组。你可以使用关键字 dtype 更改数据类型。你将在这门课程的线性代数部分深入学习单位矩阵及其用途。我们还可以使用 np.diag() 函数创建对角矩阵。对角矩阵是仅在主对角线上有值的方形矩阵。np.diag() 函数会创建一个对应于对角矩阵的 ndarray,如以下示例所示:
# Create a 4 x 4 diagonal matrix that contains the numbers 10,20,30, and 50
# on its main diagonal
X = np.diag([10,20,30,50])
# We print X
print()
print('X = \n', X)
print()
X =
[[10 0 0 0]
[ 0 20 0 0]
[ 0 0 30 0]
[ 0 0 0 50]]
NumPy 还允许你创建在给定区间内值均匀分布的 ndarray。NumPy 的np.arange() 函数非常强大,可以传入一个参数、两个参数或三个参数。下面将介绍每种情况,以及如何创建不同种类的 ndarray。
先仅向 np.arange() 中传入一个参数。如果只传入一个参数,np.arange(N) 将创建一个秩为 1 的 ndarray,其中包含从 0 到 N - 1 的连续整数。因此,注意,如果我希望数组具有介于 0 到 9 之间的整数,则需要将 N 设为 10,而不是将 N 设为 9,如以下示例所示:
# We create a rank 1 ndarray that has sequential integers from 0 to 9
x = np.arange(10)
# We print the ndarray
print()
print('x = ', x)
print()
# We print information about the ndarray
print('x has dimensions:', x.shape)
print('x is an object of type:', type(x))
print('The elements in x are of type:', x.dtype)
x = [0 1 2 3 4 5 6 7 8 9]
x has dimensions: (10,)
x is an object of type: <class 'numpy.ndarray'>
The elements in x are of type: int64
如果传入两个参数,np.arange(start,stop) 将创建一个秩为 1 的 ndarray,其中包含位于半开区间 [start, stop) 内并均匀分布的值。也就是说,均匀分布的数字将包括 start 数字,但是不包括 stop 数字。我们来看一个示例
# We create a rank 1 ndarray that has sequential integers from 4 to 9.
x = np.arange(4,10)
# We print the ndarray
print()
print('x = ', x)
print()
# We print information about the ndarray
print('x has dimensions:', x.shape)
print('x is an object of type:', type(x))
print('The elements in x are of type:', x.dtype)
x = [4 5 6 7 8 9]
x has dimensions: (6,)
x is an object of type: <class 'numpy.ndarray'>
The elements in x are of type: int64
可以看出,函数 np.arange(4,10) 生成了一个包含 4 但是不含 10 的整数序列。
最后,如果传入三个参数,np.arange(start,stop,step) 将创建一个秩为 1 的 ndarray,其中包含位于半开区间 [start, stop) 内并均匀分布的值,step 表示两个相邻值之间的差。我们来看一个示例:
# We create a rank 1 ndarray that has evenly spaced integers from 1 to 13 in steps of 3.
x = np.arange(1,14,3)
# We print the ndarray
print()
print('x = ', x)
print()
# We print information about the ndarray
print('x has dimensions:', x.shape)
print('x is an object of type:', type(x))
print('The elements in x are of type:', x.dtype)
x = [ 1 4 7 10 13]
x has dimensions: (5,)
x is an object of type: <class 'numpy.ndarray'>
The elements in x are of type: int64
虽然 np.arange() 函数允许间隔为非整数,例如 0.3,但是由于浮点数精度有限,输出通常不一致。因此,如果需要非整数间隔,通常建议使用函数 np.linspace()。np.linspace(start, stop, N) 函数返回 N 个在闭区间 [start, stop] 内均匀分布的数字。即 start 和 stop 值都包括在内。此外注意,在调用 np.linspace() 函数时,必须至少以 np.linspace(start,stop) 的形式传入两个参数。在此示例中,指定区间内的默认元素数量为 N= 50。np.linspace() 比 np.arange() 效果更好,是因为 np.linspace() 使用我们希望在特定区间内的元素数量,而不是值之间的间隔。我们来看一些示例:
# We create a rank 1 ndarray that has 10 integers evenly spaced between 0 and 25.
x = np.linspace(0,25,10)
# We print the ndarray
print()
print('x = \n', x)
print()
# We print information about the ndarray
print('x has dimensions:', x.shape)
print('x is an object of type:', type(x))
print('The elements in x are of type:', x.dtype)
x =
[ 0. 2.77777778 5.55555556 8.33333333 11.11111111 13.88888889
16.66666667 19.44444444 22.22222222 25. ]
x has dimensions: (10,)
x is an object of type: <class 'numpy.ndarray'>
The elements in x are of type: float64
从上述示例中可以看出,函数 np.linspace(0,25,10) 返回一个 ndarray,其中包含 10 个在闭区间 [0, 25] 内均匀分布的元素。还可以看出,在此示例中,起始和结束点 0 和 25 都包含在内。但是,可以不包含区间的结束点(就像 np.arange() 函数一样),方法是在 np.linspace() 函数中将关键字endpoint 设为 False。我们创建和上面一样的 x ndarray,但是这次不包含结束点:
# We create a rank 1 ndarray that has 10 integers evenly spaced between 0 and 25,
# with 25 excluded.
x = np.linspace(0,25,10, endpoint = False)
# We print the ndarray
print()
print('x = ', x)
print()
# We print information about the ndarray
print('x has dimensions:', x.shape)
print('x is an object of type:', type(x))
print('The elements in x are of type:', x.dtype)
x = [ 0. 2.5 5. 7.5 10. 12.5 15. 17.5 20. 22.5]
x has dimensions: (10,)
x is an object of type: <class 'numpy.ndarray'>
The elements in x are of type: float64
到目前为止,我们仅使用了内置函数 np.arange() 和 np.linspace() 来创建秩为 1的 ndarray。但是,我们可以将这些函数与 np.reshape() 函数相结合,创建秩为 2 的任何形状 ndarray。np.reshape(ndarray, new_shape) 函数会将给定 ndarray 转换为指定的 new_shape。请务必注意:new_shape 应该与给定 ndarray 中的元素数量保持一致。例如,你可以将秩为 1 的 6 元素 ndarray 转换为秩为 2 的 3 x 2 ndarray,或秩为 2 的 2 x 3 ndarray,因为这两个秩为 2 的数组元素总数都是 6 个。但是,你无法将秩为 1 的 6 元素 ndarray 转换为秩为 2 的 3 x 3 ndarray,因为这个秩为 2 的数组将包含 9 个元素,比原始 ndarray 中的元素数量多。我们来看一些示例:
# We create a rank 1 ndarray with sequential integers from 0 to 19
x = np.arange(20)
# We print x
print()
print('Original x = ', x)
print()
# We reshape x into a 4 x 5 ndarray
x = np.reshape(x, (4,5))
# We print the reshaped x
print()
print('Reshaped x = \n', x)
print()
# We print information about the reshaped x
print('x has dimensions:', x.shape)
print('x is an object of type:', type(x))
print('The elements in x are of type:', x.dtype)
Original x = [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]
Reshaped x =
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]]
x has dimensions: (4, 5)
x is an object of type: <class 'numpy.ndarray'>
The elements in x are of type: int64
NumPy 的一大特性是某些函数还可以当做方法使用。这样我们便能够在一行代码中按顺序应用不同的函数。ndarray 方法和 ndarray 属性相似,它们都使用点记法 (.)。我们来看看如何只用一行代码实现上述示例中的相同结果:
# We create a a rank 1 ndarray with sequential integers from 0 to 19 and
# reshape it to a 4 x 5 array
Y = np.arange(20).reshape(4, 5)
# We print Y
print()
print('Y = \n', Y)
print()
# We print information about Y
print('Y has dimensions:', Y.shape)
print('Y is an object of type:', type(Y))
print('The elements in Y are of type:', Y.dtype)
Y =
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]]
Y has dimensions: (4, 5)
Y is an object of type: <class 'numpy.ndarray'>
The elements in Y are of type: int64
可以看出,我们获得了和之前完全一样的结果。注意,当我们将 reshape() 当做方法使用时,它应用为 ndarray.reshape(new_shape)。这样会将 ndarray 转换为指定形状 new_shape。和之前一样,请注意,new_shape 应该与 ndarray 中的元素数量保持一致。在上述示例中,函数 p.arange(20) 创建了一个 ndarray 并当做将被 reshape() 方法调整形状的 ndarray。因此,如果将reshape()当做方法使用,我们不需要将 ndarray 当做参数传递给 reshape() 函数,只需传递 new_shape 参数。
同样,我们也可以使用 reshape() 与 np.linspace() 创建秩为 2 的数组,如以下示例所示。
# We create a rank 1 ndarray with 10 integers evenly spaced between 0 and 50,
# with 50 excluded. We then reshape it to a 5 x 2 ndarray
X = np.linspace(0,50,10, endpoint=False).reshape(5,2)
# We print X
print()
print('X = \n', X)
print()
# We print information about X
print('X has dimensions:', X.shape)
print('X is an object of type:', type(X))
print('The elements in X are of type:', X.dtype)
X =
[[ 0. 5.]
[10. 15.]
[20. 25.]
[30. 35.]
[40. 45.]]
X has dimensions: (5, 2)
X is an object of type: <class 'numpy.ndarray'>
The elements in X are of type: float64
# We create a 3 x 3 ndarray with random floats in the half-open interval [0.0, 1.0).
X = np.random.random((3,3))
# We print X
print()
print('X = \n', X)
print()
# We print information about X
print('X has dimensions:', X.shape)
print('X is an object of type:', type(X))
print('The elements in x are of type:', X.dtype)
X =
[[0.06328578 0.23101333 0.41896979]
[0.96269781 0.36702007 0.11999228]
[0.73906822 0.60457923 0.94556887]]
X has dimensions: (3, 3)
X is an object of type: <class 'numpy.ndarray'>
The elements in x are of type: float64
# We create a 3 x 2 ndarray with random integers in the half-open interval [4, 15).
X = np.random.randint(4,15,size=(3,2))
# We print X
print()
print('X = \n', X)
print()
# We print information about X
print('X has dimensions:', X.shape)
print('X is an object of type:', type(X))
print('The elements in X are of type:', X.dtype)
X =
[[10 8]
[ 6 6]
[ 7 11]]
X has dimensions: (3, 2)
X is an object of type: <class 'numpy.ndarray'>
The elements in X are of type: int64
NumPy 还允许我们创建由特定区间内的随机整数构成的 ndarray。函数 np.random.randint(start, stop, size = shape) 会创建一个具有给定形状的 ndarray,其中包含在半开区间 [start, stop) 内的随机整数。
在某些情况下,你可能需要创建由满足特定统计学特性的随机数字组成的 ndarray。例如,你可能希望 ndarray 中的随机数字平均值为 0。NumPy 使你能够创建从各种概率分布中抽样的数字组成的随机 ndarray。例如,函数 np.random.normal(mean, standard deviation, size=shape) 会创建一个具有给定形状的 ndarray,其中包含从正态高斯分布(具有给定均值和标准差)中抽样的随机数字。我们来创建一个 1,000 x 1,000 ndarray,其中包含从正态分布(均值为 0,标准差为 0.1)中随机抽样的浮点数。
# We create a 1000 x 1000 ndarray of random floats drawn from normal (Gaussian) distribution
# with a mean of zero and a standard deviation of 0.1.
X = np.random.normal(0, 0.1, size=(1000,1000))
# We print X
print()
print('X = \n', X)
print()
# We print information about X
print('X has dimensions:', X.shape)
print('X is an object of type:', type(X))
print('The elements in X are of type:', X.dtype)
print('The elements in X have a mean of:', X.mean())
print('The maximum value in X is:', X.max())
print('The minimum value in X is:', X.min())
print('X has', (X < 0).sum(), 'negative numbers')
print('X has', (X > 0).sum(), 'positive numbers')
X =
[[ 0.09485531 0.10425755 -0.01934186 ... 0.01909295 0.11953137
0.18458412]
[ 0.12142602 -0.11981014 -0.05996793 ... 0.0112104 0.15473444
0.03500372]
[ 0.11348749 -0.00762451 -0.082266 ... -0.10731786 -0.00303075
-0.14448409]
...
[-0.10774292 0.08075049 -0.02293864 ... 0.00144093 -0.09927305
-0.14796559]
[ 0.06260671 -0.06552191 -0.02042399 ... 0.12767425 0.16030803
-0.0159498 ]
[ 0.13377656 -0.12126549 0.04705195 ... 0.04039137 -0.09872252
-0.1062041 ]]
X has dimensions: (1000, 1000)
X is an object of type: <class 'numpy.ndarray'>
The elements in X are of type: float64
The elements in X have a mean of: -4.41283386222739e-05
The maximum value in X is: 0.4550255947372251
The minimum value in X is: -0.4816786474422222
X has 499835 negative numbers
X has 500165 positive numbers
import numpy as np
# Using the Built-in functions you learned about in the
# previous lesson, create a 4 x 4 ndarray that only
# contains consecutive even numbers from 2 to 32 (inclusive)
X = np.linspace(2,32,16).reshape(4,4)
print(X)
[[ 2. 4. 6. 8.]
[10. 12. 14. 16.]
[18. 20. 22. 24.]
[26. 28. 30. 32.]]
访问和删除 ndarray 中的元素及向其中插入元素
访问元素
# We create a rank 1 ndarray that contains integers from 1 to 5
x = np.array([1, 2, 3, 4, 5])
# We print the original x
print()
print('Original:\n x = ', x)
print()
# We change the fourth element in x from 4 to 20
x[3] = 20
# We print x after it was modified
print('Modified:\n x = ', x)
Original:
x = [1 2 3 4 5]
Modified:
x = [ 1 2 3 20 5]
#We create a 3 x 3 rank 2 ndarray that contains integers from 1 to 9
X = np.array([[1,2,3],[4,5,6],[7,8,9]])
# We print X
print()
print('X = \n', X)
print()
# Let's access some elements in X
print('This is (0,0) Element in X:', X[0,0])
print('This is (0,1) Element in X:', X[0,1])
print('This is (2,2) Element in X:', X[2,2])
X =
[[1 2 3]
[4 5 6]
[7 8 9]]
This is (0,0) Element in X: 1
This is (0,1) Element in X: 2
This is (2,2) Element in X: 9
# We create a 3 x 3 rank 2 ndarray that contains integers from 1 to 9
X = np.array([[1,2,3],[4,5,6],[7,8,9]])
# We print the original x
print()
print('Original:\n X = \n', X)
print()
# We change the (0,0) element in X from 1 to 20
X[0,0] = 20
# We print X after it was modified
print('Modified:\n X = \n', X)
Original:
X =
[[1 2 3]
[4 5 6]
[7 8 9]]
Modified:
X =
[[20 2 3]
[ 4 5 6]
[ 7 8 9]]
删除元素
现在看看如何向 ndarray 中添加元素及删除其中的元素。我们可以使用 np.delete(ndarray, elements, axis) 函数删除元素。此函数会沿着指定的轴从给定 ndarray 中删除给定的元素列表。对于秩为 1 的 ndarray,不需要使用关键字 axis。对于秩为 2 的 ndarray,axis = 0 表示选择行,axis = 1 表示选择列。
# We create a rank 1 ndarray
x = np.array([1, 2, 3, 4, 5])
# We create a rank 2 ndarray
Y = np.array([[1,2,3],[4,5,6],[7,8,9]])
# We print x
print()
print('Original x = ', x)
# We delete the first and last element of x
x = np.delete(x,[0,4])
# We print x with the first and last element deleted
print()
print('Modified x = ', x)
# We print Y
print()
print('Original Y = \n', Y)
# We delete the first row of y
w = np.delete(Y, 0, axis=0)
# We delete the first and last column of y
v = np.delete(Y, [0,2], axis=1)
# We print w
print()
print('w = \n', w)
# We print v
print()
print('v = \n', v)
Original x = [1 2 3 4 5]
Modified x = [2 3 4]
Original Y =
[[1 2 3]
[4 5 6]
[7 8 9]]
w =
[[4 5 6]
[7 8 9]]
v =
[[2]
[5]
[8]]
添加元素
现在我们来看看如何向 ndarray 中附加值。我们可以使用 np.append(ndarray, elements, axis) 函数向 ndarray 中附加值。该函数会将给定的元素列表沿着指定的轴附加到 ndarray 中。
# We create a rank 1 ndarray
x = np.array([1, 2, 3, 4, 5])
# We create a rank 2 ndarray
Y = np.array([[1,2,3],[4,5,6]])
# We print x
print()
print('Original x = ', x)
# We append the integer 6 to x
x = np.append(x, 6)
# We print x
print()
print('x = ', x)
# We append the integer 7 and 8 to x
x = np.append(x, [7,8])
# We print x
print()
print('x = ', x)
# We print Y
print()
print('Original Y = \n', Y)
# We append a new row containing 7,8,9 to y
v = np.append(Y, [[7,8,9]], axis=0)
# We append a new column containing 9 and 10 to y
q = np.append(Y,[[9],[10]], axis=1)
# We print v
print()
print('v = \n', v)
# We print q
print()
print('q = \n', q)
Original x = [1 2 3 4 5]
x = [1 2 3 4 5 6]
x = [1 2 3 4 5 6 7 8]
Original Y =
[[1 2 3]
[4 5 6]]
v =
[[1 2 3]
[4 5 6]
[7 8 9]]
q =
[[ 1 2 3 9]
[ 4 5 6 10]]
我们可以使用 np.insert(ndarray, index, elements, axis) 函数向 ndarray 中插入值。
# We create a rank 1 ndarray
x = np.array([1, 2, 5, 6, 7])
# We create a rank 2 ndarray
Y = np.array([[1,2,3],[7,8,9]])
# We print x
print()
print('Original x = ', x)
# We insert the integer 3 and 4 between 2 and 5 in x.
x = np.insert(x,2,[3,4])
# We print x with the inserted elements
print()
print('x = ', x)
# We print Y
print()
print('Original Y = \n', Y)
# We insert a row between the first and last row of y
w = np.insert(Y,1,[4,5,6],axis=0)
# We insert a column full of 5s between the first and second column of y
v = np.insert(Y,1,5, axis=1)
# We print w
print()
print('w = \n', w)
# We print v
print()
print('v = \n', v)
Original x = [1 2 5 6 7]
x = [1 2 3 4 5 6 7]
Original Y =
[[1 2 3]
[7 8 9]]
w =
[[1 2 3]
[4 5 6]
[7 8 9]]
v =
[[1 5 2 3]
[7 5 8 9]]
NumPy 还允许我们将 ndarray 上下堆叠起来,或者左右堆叠。可以使用np.vstack()函数进行垂直堆叠,或使用 np.hstack() 函数进行水平堆叠。请务必注意,为了堆叠 ndarray,ndarray 的形状必须相符。
# We create a rank 1 ndarray
x = np.array([1,2])
# We create a rank 2 ndarray
Y = np.array([[3,4],[5,6]])
# We print x
print()
print('x = ', x)
# We print Y
print()
print('Y = \n', Y)
# We stack x on top of Y
z = np.vstack((x,Y))
# We stack x on the right of Y. We need to reshape x in order to stack it on the right of Y.
w = np.hstack((Y,x.reshape(2,1)))
# We print z
print()
print('z = \n', z)
# We print w
print()
print('w = \n', w)
x = [1 2]
Y =
[[3 4]
[5 6]]
z =
[[1 2]
[3 4]
[5 6]]
w =
[[3 4 1]
[5 6 2]]
切片操作
正如之前提到的,我们除了能够一次访问一个元素之外,NumPy 还提供了访问 ndarray 子集的方式,称之为切片。切片方式是在方括号里用冒号 : 分隔起始和结束索引。通常,你将遇到三种类型的切片:
2. ndarray[start:]
3. ndarray[:end]```
第一种方法用于选择在 `start` 和 `end` 索引之间的元素。第二种方法用于选择从 `start` 索引开始直到`最后一个`索引的所有元素。第三种方法用于选择从`第一个索引`开始直到 `end` 索引的所有元素。请注意,在`第一种方法和第三种方法中`,`结束索引`不包括在内。此外注意,因为 ndarray 可以是多维数组,在进行切片时,通常需要为数组的每个维度指定一个切片。
```python
# We create a 4 x 5 ndarray that contains integers from 0 to 19
X = np.arange(20).reshape(4, 5)
# We print X
print()
print('X = \n', X)
print()
# We select all the elements that are in the 2nd through 4th rows and in the 3rd to 5th columns
Z = X[1:4,2:5]
# We print Z
print('Z = \n', Z)
# We can select the same elements as above using method 2
W = X[1:,2:5]
# We print W
print()
print('W = \n', W)
# We select all the elements that are in the 1st through 3rd rows and in the 3rd to 5th columns
Y = X[:3,2:5]
# We print Y
print()
print('Y = \n', Y)
# We select all the elements in the 3rd row
v = X[2,:]
# We print v
print()
print('v = ', v)
# We select all the elements in the 3rd column
q = X[:,2]
# We print q
print()
print('q = ', q)
# We select all the elements in the 3rd column but return a rank 2 ndarray
R = X[:,2:3]
# We print R
print()
print('R = \n', R)
X =
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]]
Z =
[[ 7 8 9]
[12 13 14]
[17 18 19]]
W =
[[ 7 8 9]
[12 13 14]
[17 18 19]]
Y =
[[ 2 3 4]
[ 7 8 9]
[12 13 14]]
v = [10 11 12 13 14]
q = [ 2 7 12 17]
R =
[[ 2]
[ 7]
[12]
[17]]
注意,当我们选择第 3 列中的所有元素,即上述变量 q,切片返回一个秩为 1 的 ndarray,而不是秩为 2 的 ndarray。但是,如果以稍微不同的方式切片X,即上述变量 R,实际上可以获得秩为 2 的 ndarray。
请务必注意,如果对 ndarray 进行切片并将结果保存到新的变量中,就像之前一样,数据不会复制到新的变量中。初学者对于这一点经常比较困惑。因此,我们将深入讲解这方面的知识。在上述示例中,当我们进行赋值时,例如:
Z = X[1:4,2:5]
原始数组X的切片没有复制到变量 Z 中。X 和 Z 现在只是同一个 ndarray 的两个不同名称。我们提到,切片只是创建了原始数组的一个视图。也就是说,如果对 Z 做出更改,也会更改 X 中的元素。我们来看一个示例:
# We create a 4 x 5 ndarray that contains integers from 0 to 19
X = np.arange(20).reshape(4, 5)
# We print X
print()
print('X = \n', X)
print()
# We select all the elements that are in the 2nd through 4th rows and in the 3rd to 5th columns
Z = X[1:4,2:5]
# We print Z
print()
print('Z = \n', Z)
print()
# We change the last element in Z to 555
Z[2,2] = 555
# We print X
print()
print('X = \n', X)
print()
X =
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]]
Z =
[[ 7 8 9]
[12 13 14]
[17 18 19]]
X =
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[ 10 11 12 13 14]
[ 15 16 17 18 555]]
但是,如果我们想创建一个新的 ndarray,其中包含切片中的值的副本,需要使用 np.copy()函数。np.copy(ndarray) 函数会创建给定 ndarray 的一个副本。此函数还可以当做方法使用,就像之前使用 reshape 函数一样。我们来看看之前的相同示例,但是现在创建数组副本。我们将 copy 同时当做函数和方法。
# We create a 4 x 5 ndarray that contains integers from 0 to 19
X = np.arange(20).reshape(4, 5)
# We print X
print()
print('X = \n', X)
print()
# create a copy of the slice using the np.copy() function
Z = np.copy(X[1:4,2:5])
# create a copy of the slice using the copy as a method
W = X[1:4,2:5].copy()
# We change the last element in Z to 555
Z[2,2] = 555
# We change the last element in W to 444
W[2,2] = 444
# We print X
print()
print('X = \n', X)
# We print Z
print()
print('Z = \n', Z)
# We print W
print()
print('W = \n', W)
print(X)
X =
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]]
X =
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]]
Z =
[[ 7 8 9]
[ 12 13 14]
[ 17 18 555]]
W =
[[ 7 8 9]
[ 12 13 14]
[ 17 18 444]]
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]]
可以清晰地看出,通过使用copy命令,我们创建了完全相互独立的新 ndarray。
通常,我们会使用一个 ndarray 对另一个 ndarray 进行切片、选择或更改另一个 ndarray 的元素。我们来看一些示例:
# We create a 4 x 5 ndarray that contains integers from 0 to 19
X = np.arange(20).reshape(4, 5)
# We create a rank 1 ndarray that will serve as indices to select elements from X
indices = np.array([1,3])
# We print X
print()
print('X = \n', X)
print()
# We print indices
print('indices = ', indices)
print()
# We use the indices ndarray to select the 2nd and 4th row of X
Y = X[indices,:]
# We use the indices ndarray to select the 2nd and 4th column of X
Z = X[:, indices]
# We print Y
print()
print('Y = \n', Y)
# We print Z
print()
print('Z = \n', Z)
X =
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]]
indices = [1 3]
Y =
[[ 5 6 7 8 9]
[15 16 17 18 19]]
Z =
[[ 1 3]
[ 6 8]
[11 13]
[16 18]]
NumPy 还提供了从 ndarray 中选择特定元素的内置函数。例如,np.diag(ndarray, k=N) 函数会以 N 定义的对角线提取元素。默认情况下,k=0,表示主对角线。k > 0 的值用于选择在主对角线之上的对角线中的元素,k < 0 的值用于选择在主对角线之下的对角线中的元素。我们来看一个示例:
# We create a 5 x 5 ndarray that contains integers from 0 to 24
X = np.arange(25).reshape(5, 5)
# We print X
print()
print('X = \n', X)
print()
# We print the elements in the main diagonal of X
print('z =', np.diag(X))
print()
# We print the elements above the main diagonal of X
print('y =', np.diag(X, k=1))
print()
# We print the elements below the main diagonal of X
print('w = ', np.diag(X, k=-1))
X =
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]
[20 21 22 23 24]]
z = [ 0 6 12 18 24]
y = [ 1 7 13 19]
w = [ 5 11 17 23]
布尔型索引、集合运算和排序
到目前为止,我们了解了如何使用索引进行切片以及选择 ndarray 元素。当我们知道要选择的元素的确切索引时,这些方法很有用。但是,在很多情况下,我们不知道要选择的元素的索引。例如,假设有一个 10,000 x 10,000 ndarray,其中包含从 1 到 15,000 的随机整数,我们只想选择小于 20 的整数。这时候就要用到布尔型索引,对于布尔型索引,我们将使用逻辑参数(而不是确切的索引)选择元素。我们来看一些示例:
# We create a 5 x 5 ndarray that contains integers from 0 to 24
X = np.arange(25).reshape(5, 5)
# We print X
print()
print('Original X = \n', X)
print()
# We use Boolean indexing to select elements in X:
print('The elements in X that are greater than 10:', X[X > 10])
print('The elements in X that lees than or equal to 7:', X[X <= 7])
print('The elements in X that are between 10 and 17:', X[(X > 10) & (X < 17)])
# We use Boolean indexing to assign the elements that are between 10 and 17 the value of -1
X[(X > 10) & (X < 17)] = -1
# We print X
print()
print('X = \n', X)
print()
Original X =
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]
[20 21 22 23 24]]
The elements in X that are greater than 10: [11 12 13 14 15 16 17 18 19 20 21 22 23 24]
The elements in X that lees than or equal to 7: [0 1 2 3 4 5 6 7]
The elements in X that are between 10 and 17: [11 12 13 14 15 16]
X =
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 -1 -1 -1 -1]
[-1 -1 17 18 19]
[20 21 22 23 24]]
例如查找两个 ndarray 中的相同元素。我们来看一些示例:
# We create a rank 1 ndarray
x = np.array([1,2,3,4,5])
# We create a rank 1 ndarray
y = np.array([6,7,2,8,4])
# We print x
print()
print('x = ', x)
# We print y
print()
print('y = ', y)
# We use set operations to compare x and y:
print()
print('The elements that are both in x and y:', np.intersect1d(x,y))
print('The elements that are in x that are not in y:', np.setdiff1d(x,y))
print('All the elements of x and y:',np.union1d(x,y))
x = [1 2 3 4 5]
y = [6 7 2 8 4]
The elements that are both in x and y: [2 4]
The elements that are in x that are not in y: [1 3 5]
All the elements of x and y: [1 2 3 4 5 6 7 8]
我们还可以在 NumPy 中对 ndarray 进行排序。我们将了解如何使用 np.sort() 函数以不同的方式对秩为 1 和 2 的 ndarray 进行排序。和我们之前看到的其他函数一样,sort 函数也可以当做方法使用。但是,对于此函数来说,数据在内存中的存储方式有很大变化。当 np.sort() 当做函数使用时,它不会对ndarray进行就地排序,即不更改被排序的原始 ndarray。但是,如果将 sort 当做方法,ndarray.sort() 会就地排序 ndarray,即原始数组会变成排序后的数组。我们来看一些示例:
# We sort x but only keep the unique elements in x
print(np.sort(np.unique(x)))
[1 2 3 4 5]
# We create an unsorted rank 1 ndarray
x = np.random.randint(1,11,size=(10,))
# We print x
print()
print('Original x = ', x)
# We sort x and print the sorted array using sort as a method.
x.sort()
# When we sort in place the original array is changed to the sorted array. To see this we print x again
print()
print('x after sorting:', x)
Original x = [ 9 10 2 8 6 3 1 8 2 2]
x after sorting: [ 1 2 2 2 3 6 8 8 9 10]
在对秩为 2 的 ndarray 进行排序时,我们需要在 np.sort() 函数中指定是按行排序,还是按列排序。为此,我们可以使用关键字 axis。我们来看一些示例:
# We create an unsorted rank 2 ndarray
X = np.random.randint(1,11,size=(5,5))
# We print X
print()
print('Original X = \n', X)
print()
# We sort the columns of X and print the sorted array
print()
print('X with sorted columns :\n', np.sort(X, axis = 0))
# We sort the rows of X and print the sorted array
print()
print('X with sorted rows :\n', np.sort(X, axis = 1))
Original X =
[[ 8 4 6 9 7]
[10 3 10 5 7]
[ 4 10 2 5 8]
[ 8 9 7 3 4]
[ 3 1 1 4 10]]
X with sorted columns :
[[ 3 1 1 3 4]
[ 4 3 2 4 7]
[ 8 4 6 5 7]
[ 8 9 7 5 8]
[10 10 10 9 10]]
X with sorted rows :
[[ 4 6 7 8 9]
[ 3 5 7 10 10]
[ 2 4 5 8 10]
[ 3 4 7 8 9]
[ 1 1 3 4 10]]
算术运算和广播
我们已经学到“ NumPy ”课程的最后一节课了。在最后一节课,我们将了解 NumPy 如何对 ndarray 进行算术运算。NumPy 允许对 ndarray 执行元素级运算以及矩阵运算。在这节课,我们将仅了解如何对 ndarray 进行元素级运算。为了进行元素级运算,NumPy 有时候会用到广播功能。广播一词用于描述 NumPy 如何对具有不同形状的 ndarray 进行元素级算术运算。例如,在标量和 ndarray 之间进行算术运算时,会隐式地用到广播。
请注意,在进行元素级运算时,对其执行运算的 ndarray 必须具有相同的形状或者可以广播。我们将在这节课的稍后阶段详细讲解这方面的知识。我们先对秩为 1 的 ndarray 执行元素级算术运算:
# We create two rank 1 ndarrays
x = np.array([1,2,3,4])
y = np.array([5.5,6.5,7.5,8.5])
# We print x
print()
print('x = ', x)
# We print y
print()
print('y = ', y)
print()
# We perfrom basic element-wise operations using arithmetic symbols and functions
print('x + y = ', x + y)
print('add(x,y) = ', np.add(x,y))
print()
print('x - y = ', x - y)
print('subtract(x,y) = ', np.subtract(x,y))
print()
print('x * y = ', x * y)
print('multiply(x,y) = ', np.multiply(x,y))
print()
print('x / y = ', x / y)
print('divide(x,y) = ', np.divide(x,y))
x = [1 2 3 4]
y = [5.5 6.5 7.5 8.5]
x + y = [ 6.5 8.5 10.5 12.5]
add(x,y) = [ 6.5 8.5 10.5 12.5]
x - y = [-4.5 -4.5 -4.5 -4.5]
subtract(x,y) = [-4.5 -4.5 -4.5 -4.5]
x * y = [ 5.5 13. 22.5 34. ]
multiply(x,y) = [ 5.5 13. 22.5 34. ]
x / y = [0.18181818 0.30769231 0.4 0.47058824]
divide(x,y) = [0.18181818 0.30769231 0.4 0.47058824]
我们还可以对秩为 2 的 ndarray 执行相同的元素级算术运算
# We create two rank 2 ndarrays
X = np.array([1,2,3,4]).reshape(2,2)
Y = np.array([5.5,6.5,7.5,8.5]).reshape(2,2)
# We print X
print()
print('X = \n', X)
# We print Y
print()
print('Y = \n', Y)
print()
# We perform basic element-wise operations using arithmetic symbols and functions
print('X + Y = \n', X + Y)
print()
print('add(X,Y) = \n', np.add(X,Y))
print()
print('X - Y = \n', X - Y)
print()
print('subtract(X,Y) = \n', np.subtract(X,Y))
print()
print('X * Y = \n', X * Y)
print()
print('multiply(X,Y) = \n', np.multiply(X,Y))
print()
print('X / Y = \n', X / Y)
print()
print('divide(X,Y) = \n', np.divide(X,Y))
X =
[[1 2]
[3 4]]
Y =
[[5.5 6.5]
[7.5 8.5]]
X + Y =
[[ 6.5 8.5]
[10.5 12.5]]
add(X,Y) =
[[ 6.5 8.5]
[10.5 12.5]]
X - Y =
[[-4.5 -4.5]
[-4.5 -4.5]]
subtract(X,Y) =
[[-4.5 -4.5]
[-4.5 -4.5]]
X * Y =
[[ 5.5 13. ]
[22.5 34. ]]
multiply(X,Y) =
[[ 5.5 13. ]
[22.5 34. ]]
X / Y =
[[0.18181818 0.30769231]
[0.4 0.47058824]]
divide(X,Y) =
[[0.18181818 0.30769231]
[0.4 0.47058824]]
# We create a rank 1 ndarray
x = np.array([1,2,3,4])
# We print x
print()
print('x = ', x)
# We apply different mathematical functions to all elements of x
print()
print('EXP(x) =', np.exp(x))
print()
print('SQRT(x) =',np.sqrt(x))
print()
print('POW(x,2) =',np.power(x,2)) # We raise all elements to the power of 2
x = [1 2 3 4]
EXP(x) = [ 2.71828183 7.3890561 20.08553692 54.59815003]
SQRT(x) = [1. 1.41421356 1.73205081 2. ]
POW(x,2) = [ 1 4 9 16]
NumPy 的另一个重要特性是具有大量不同的统计学函数。统计学函数为我们提供了关于 ndarray 中元素的统计学信息。我们来看一些示例:
# We create a 2 x 2 ndarray
X = np.array([[1,2], [3,4]])
# We print x
print()
print('X = \n', X)
print()
z = np.delete()
print('Average of all elements in X:', X.mean())
print('Average of all elements in the columns of X:', X.mean(axis=0))
print('Average of all elements in the rows of X:', X.mean(axis=1))
print()
print('Sum of all elements in X:', X.sum())
print('Sum of all elements in the columns of X:', X.sum(axis=0))
print('Sum of all elements in the rows of X:', X.sum(axis=1))
print()
print('Standard Deviation of all elements in X:', X.std())
print('Standard Deviation of all elements in the columns of X:', X.std(axis=0))
print('Standard Deviation of all elements in the rows of X:', X.std(axis=1))
print()
print('Median of all elements in X:', np.median(X))
print('Median of all elements in the columns of X:', np.median(X,axis=0))
print('Median of all elements in the rows of X:', np.median(X,axis=1))
print()
print('Maximum value of all elements in X:', X.max())
print('Maximum value of all elements in the columns of X:', X.max(axis=0))
print('Maximum value of all elements in the rows of X:', X.max(axis=1))
print()
print('Minimum value of all elements in X:', X.min())
print('Minimum value of all elements in the columns of X:', X.min(axis=0))
print('Minimum value of all elements in the rows of X:', X.min(axis=1))
X =
[[1 2]
[3 4]]
Average of all elements in X: 2.5
Average of all elements in the columns of X: [2. 3.]
Average of all elements in the rows of X: [1.5 3.5]
Sum of all elements in X: 10
Sum of all elements in the columns of X: [4 6]
Sum of all elements in the rows of X: [3 7]
Standard Deviation of all elements in X: 1.118033988749895
Standard Deviation of all elements in the columns of X: [1. 1.]
Standard Deviation of all elements in the rows of X: [0.5 0.5]
Median of all elements in X: 2.5
Median of all elements in the columns of X: [2. 3.]
Median of all elements in the rows of X: [1.5 3.5]
Maximum value of all elements in X: 4
Maximum value of all elements in the columns of X: [3 4]
Maximum value of all elements in the rows of X: [2 4]
Minimum value of all elements in X: 1
Minimum value of all elements in the columns of X: [1 2]
Minimum value of all elements in the rows of X: [1 3]
# We create a 2 x 2 ndarray
X = np.array([[1,2], [3,4]])
# We print x
print()
print('X = \n', X)
print()
print('3 * X = \n', 3 * X)
print()
print('3 + X = \n', 3 + X)
print()
print('X - 3 = \n', X - 3)
print()
print('X / 3 = \n', X / 3)
X =
[[1 2]
[3 4]]
3 * X =
[[ 3 6]
[ 9 12]]
3 + X =
[[4 5]
[6 7]]
X - 3 =
[[-2 -1]
[ 0 1]]
X / 3 =
[[0.33333333 0.66666667]
[1. 1.33333333]]
# We create a rank 1 ndarray
x = np.array([1,2,3])
# We create a 3 x 3 ndarray
Y = np.array([[1,2,3],[4,5,6],[7,8,9]])
# We create a 3 x 1 ndarray
Z = np.array([1,2,3]).reshape(3,1)
# We print x
print()
print('x = ', x)
print()
# We print Y
print()
print('Y = \n', Y)
print()
# We print Z
print()
print('Z = \n', Z)
print()
print('x + Y = \n', x + Y)
print()
print('Z + Y = \n',Z + Y)
x = [1 2 3]
Y =
[[1 2 3]
[4 5 6]
[7 8 9]]
Z =
[[1]
[2]
[3]]
x + Y =
[[ 2 4 6]
[ 5 7 9]
[ 8 10 12]]
Z + Y =
[[ 2 3 4]
[ 6 7 8]
[10 11 12]]
import numpy as np
# Use Broadcasting to create a 4 x 4 ndarray that has its first
# column full of 1s, its second column full of 2s, its third
# column full of 3s, etc..
# Do not change the name of this array.
# Please don't print anything from your code! The TEST RUN button below will print your array.
X = np.ones((4,4)) * np.arange(1,5)
print(X)
[[1. 2. 3. 4.]
[1. 2. 3. 4.]
[1. 2. 3. 4.]
[1. 2. 3. 4.]]