导入numpy数据包
- # 引入Numpy库
- import numpy as np
ndarray.ndmin查询数组的维度
- import numpy as np
- # 数组维度
- ## 维度为1
- arr1 = np.array([1,2,3])
- arr1.ndim # 1
- ## 维度为2
- arr2 = np.array([[1,2,3],[4,5,6]])
- arr2.ndim # 2
- ## 维度为3
- arr3 = np.array([
- [[1,2,3],[4,5,6]],
- [[7,8,9],[10,11,12]]
- ])
- arr3.ndim # 3
ndarray.shape查询数组的形状(几行几列),返回值是一个元组,里面有几个元素代表是几维数组
- import numpy as np
- arr1 = np.array([1,2,3])
- arr1.shape # (3,)
-
- arr2 = np.array([[1,2,3],[4,5,6]])
- arr2.shape # (2,3)
-
- arr3 = np.array([
- [[1,2,3],[4,5,6]],
- [[7,8,9],[10,11,12]]
- ])
- arr3.shape # (2,2,3)
ndarray.shape也可以改变数组形状
- import numpy as np
- arr4 = np.array([[1,2,3],[4,5,6]])
- arr4.shape = (3,2)
arr4
arr4(处理后)
.reshape函数可以改变原数组的形状,创建一个新数组,改变新数组的元素,原数组对应元素的值也会发生改变
- # NumPy提供了.reshape函数来调整数组大小形状
- import numpy as np
-
- data = np.array([[1,2,3],[4,5,6]]) # array([[1, 2, 3],
- # [4, 5, 6]])
- data.shape # (2,3)
-
- arr = data.reshape(6,) # array([1, 2, 3, 4, 5, 6])
- arr.shape # (6,)
-
- arr[0] = 437
- arr # array([437, 2, 3, 4, 5, 6])
-
- data # array([[437, 2, 3],
- # [ 4, 5, 6]])
.flatten函数可实现扁平化(多维数组转化为一维数组)
- import numpy as np
-
- arr = np.array([
- [[1,2,3],[4,5,6]],
- [[7,8,9],[10,11,12]]
- ])
- arr.ndim # 3
-
- deal_arr = arr.flatten() # array([1,2,3,4,5,6,7,8,9,10,11,12])
- deal_arr.ndim # 1
ndarray.size查询数组元素个数
ndarray.itemsize查询数组中每个元素所占内存的大小(以字节为单位)
- import numpy as np
-
- arr = np.array([
- [[1,2,3],[4,5,6]],
- [[7,8,9],[10,11,12]]
- ])
- # 数组的元素个数
- arr.size # 12
- # 各元素所占内存
- arr.itemsize # 4
- # 各元素的数据类型
- arr.dtype # dtype('int32')
- # 数组所占内存
- arr.itemsize * arr.size # 48
-
- # 数组的dtype为int8(一个字节)
- data1 = np.array([1,2,3,4,5], dtype = np.int8)
- data1.itemsize # 1
-
- # 数组的dtype现在为float64(八个字节)
- data2 = np.array([1,2,3,4,5], dtype = np.float64)
- data2.itemsize # 8
ndarray.dtype用于返回ndarray对象的元素类型
- import numpy as np
- arr1 = np.array([[1,2,3],[4,5,6]])
- arr1.dtype # dtype('int32')
- arr2 = np.array([1.2, 2.3, 3.4])
- arr2.dtype # dtype('float64')