Python中的NumPy
简介:
NumPy是一个用于处理数组的python库。
NumPy是Numerical Python的缩写。
为什么使用NumPy?
- python中的列表与数组的作用相同,但它们的处理速度太慢。
- NumPy提供了一个数组对象,它比传统的python列表快50倍。
导入NumPy :
import numpy
现在,它已经可以使用了。
import numpy
a=numpy.array([1,2,3])
print(a)
用别名导入NumPy :
通常,numpy 是用 np 别名导入的。
alias : alias是引用同一事物的替代名称。
import numpy as np
a=np.array([1,2,3])
print(a)
用NumPy创建数组。
array() numpy的方法是用来在numpy中创建数组的。numpy中的数组对象被称为ndarray。
import numpy as np
a=np.array([1,2,3])
print(a)
print(type(a))
type() 函数会告诉你传递给它的对象的类型。
你可以在数组中传递任何列表、元组、字典,它将被转换为ndarray对象。
数组中的尺寸。
- 0-D数组。
import numpy as np
a=np.array(42)
print(a)
- 1-D数组。
import numpy as np
a=np.array([1,2,3])
print(a)
- 2-D数组。
import numpy as np
a=np.array([[1,2,3],[4,5,6]])
print(a)
- 3-D数组。
import numpy as np
a=np.array([[[1,2,3],[4,5,6]],[7,8,9],[9,1,2]]])
print(a)
你也可以借助python中的ndim 属性来检查数组中的维数。
import numpy as np
a=np.array([[1,2,3],[4,5,6]])
print(a.ndim)
NumPy索引。
我们可以通过引用其索引号来访问数组元素。
numpy中的索引从0开始,第一个元素有索引0,第二个元素有索引1,以此类推。
#Get the first element from an array :
import numpy as np
a=np.array([1,2,3])
print(a[0])
# Get the second and third element and add them :
import numpy as np
a=np.array([1,2,3,4,5])
print(a[1]+a[2])
访问二维数组。
要访问二维数组中的元素,你可以写成[row index number,column index number]
#Access the element on the first row and second column:
import numpy as np
a=np.array([[1,2,3,4]],[5,6,7,8]])
print(a[0,1])
负索引。
负数的索引从末尾的-1开始。
#Print the last element from 2nd dimension :
import numpy as np
a=np.array([[1,2,3,4],[5,6,7,8]])
print(a[1,-1])
NumPy中的分片。
切片是指从一个给定的索引到另一个给定的索引来获取元素。
我们可以像这样传递分片。
[start:end:step]
- 如果你不传递起始点,默认是0。
- 如果你不传递结束点,默认是维度的长度。
- 如果你不传递步骤,默认为1。
#Slice elements from index 1 to index 5 :
import numpy as np
a=np.array([1,2,3,4,5,6])
print(a[1:5])
#Slice elements from index 4 to the end of the array :
import numpy as np
a=np.array([1,2,3,4,5,6])
print(a[4::])
负数切分。
#Slice from index 3 from the end to index 1 from the end :
import numpy as np
a=np.array([1,2,3,4,5,6])
print(a[-3:-1])
阶梯式切片。
#Return every other element from index 1 to index 5 :
import numpy as np
a=np.array([1,2,3,4,5,6])
print(a[1:5:2])
切分二维数组。
# From the second array slice the elements from index 1 to index 4 :
import numpy as np
a=np.array([[1,2,3,4,5,6,7],[7,8,9,8,7,6,5]])
print(a[1,1:4]
检查数组的数据类型。
你可以使用dtype 属性检查数组中的元素的数据类型。
import numpy as np
a=np.array([1,2,3,4,5])
print(a.dtype)
阵列的形状。
阵列的形状是阵列中的行和列的数量。
shape numpy的属性返回行和列的数量的元组。
#Print the shape of 2-D Array :
import numpy as np
a=np.array([[1,2,3],[4,5,6]])
print(a.shape)
重塑一个数组。
重塑一个数组意味着改变一个数组的形状。
#Convert the following 1-D Array into 2-D Array :
import numpy as np
a=np.array([1,2,3,4,5,6,7,8,9,10,11,12])
x=a.reshape(3,4)
print(x)