代码
### 数组创建
# 导入模块,并重命名为np
import numpy as np
# 单个列表创建一维数组
arr1 = np.array([3,10,8,7,34,11,28,72])
# 嵌套元组创建二维数组
arr2 = np.array(((8.5,6,4.1,2,0.7),(1.5,3,5.4,7.3,9),(3.2,3,3.8,3,3),(11.2,13.4,15.6,17.8,19)))
print('一维数组:n',arr1)
print('二维数组:n',arr2)
结果
数组元素获取## 元素获取 # 一维数组元素的获取 print(arr1[[2,3,5,7]]) # 二维数组元素的获取 # 第2行第3列元素 print(arr2[1,2]) # 第3行所有元素 print(arr2[2,:]) # 第2列所有元素 print(arr2[:,1]) # 第2至4行,2至5行 print(arr2[1:4,1:5])
结果
# ix_函数 # 第一行、最后一行和第二列、第四列构成的数组 print(arr2[np.ix_([0,-1],[1,3])]) # 前面表示行门后面表示列 # 第一行、最后一行和第一列、第三列、第四列构成的数组 print(arr2[np.ix_([0,-1],[1,2,3])])
结果
数组的常用属性
### 数组的常用属性 # 读入数据 import numpy as np stu_score = np.genfromtxt(fname = r'C:UsersChenypython数据分析与挖掘stu_socre.txt',delimiter='t',skip_header=1) # 查看数据结构 print(type(stu_score)) # 查看数据维数 print(stu_score.ndim) # 查看数据行列数 print(stu_score.shape) # 查看数组元素的数据类型 print(stu_score.dtype) # 查看数组元素个数 print(stu_score.size)
结果
更改数组形状 reshape和resize
### 更改数组的型状 arr3 = np.array([[1,5,7],[3,6,1],[2,4,8],[5,8,9],[1,5,9],[8,5,2]]) # 数组的行列数 print(arr3.shape) # 使用reshape方法更改数组的形状 print(arr3.reshape(2,9)) # 打印数组arr3的行列数 print(arr3.shape) arr3 = np.array([[1,5,7],[3,6,1],[2,4,8],[5,8,9],[1,5,9],[8,5,2]]) # 使用resize方法更改数组的形状 print(arr3.resize(2,9)) # 打印数组arr3的行列数 print(arr3.shape)
结果
降维:ravel、fatten
arr4 = np.array([[1,10,100],[2,20,200],[3,30,300]])
print('原数组:n',arr4)
# 默认排序降维
print('数组降维:n',arr4.ravel())
print(arr4.flatten())
print(arr4.reshape(-1))
# 改变排序模式的降维
print("改变排序模式的降维")
print(arr4.ravel(order = 'F'))
print(arr4.flatten(order = 'F'))
print(arr4.reshape(-1, order = 'F'))
结果
差别
# 更改预览值
arr4.flatten()[0] = 2000 # flatten修改不会影响原数组
print('flatten方法:n',arr4)
arr4.ravel()[1] = 1000
print('ravel方法:n',arr4)
arr4.reshape(-1)[2] = 3000
print('reshape方法:n',arr4)
结果
合并
arr5 = np.array([1,2,3])
print(arr4,"n",arr5)
print('vstack纵向合并数组:n',np.vstack([arr4,arr5]))
print('row_stack纵向合并数组:n',np.row_stack([arr4,arr5]))
结果
arr6 = np.array([[5],[15],[25]])
print(arr4,"n",arr6)
print('hstack横向合并数组:n',np.hstack([arr4,arr6]))
print('column_stack横向合并数组:n',np.column_stack([arr4,arr6]))
结果



