python工具包--Numpy


官方的API参考文档: https://numpy.org/doc/stable/reference/index.html

Numpy的基本操作

array = np.array([1,2,3,4,5])
print(type(array))
<class 'numpy.ndarray'>
array
array([1, 2, 3, 4, 5])
array2 = array + 1
array2
array([2, 3, 4, 5, 6])
array2 + array

array([ 3,  5,  7,  9, 11])
array2*array
array([ 2,  6, 12, 20, 30])
# python的数据list结构,shape是可以用在numpy中
tang_list = [1,2,3,4,5]
tang_list.shape
---------------------------------------------------------------------------

AttributeError                            Traceback (most recent call last)

<ipython-input-25-c799f36c95f6> in <module>
      1 tang_list = [1,2,3,4,5]
----> 2 tang_list.shape


AttributeError: 'list' object has no attribute 'shape'

可见,python中的list结构是没有list属性的,numpy中的array数组结构才有着一个属性

tang_list = [1,2,3,4,5]
# 另外的一个定义方法
# tang_array = np.array([1,2,3,4,5])
tang_array = np.array(tang_list)
tang_array
array([1, 2, 3, 4, 5])

需要注意,ndarray中所有元素必须是同一个类型,否则会自动的向下转换:int-》float-》str

# 打印当前的数据格式
type(tang_array)
numpy.ndarray
# 打印当前数据类型
tang_array.dtype
dtype('int32')
# 打印当前数组中元素个数
tang_array.size
5
# 打印当前数据的维度
tang_array.ndim
1
# 打印出结果(5)表示其中有五个元素,而当前数组的维数是1维的,所有shape可以同时打印出维度和个数
array.shape
(5,)

索引与切片操作

# tang_array = array([1,2,3,4,5])
tang_array[1:3]
array([2, 3])
# 打印第二元素开始到第四个元素
print(tang_array[2:4])
[3 4]
# 打印从后往前的三个元素
tang_array[-3:]
array([3, 4, 5])
# 定义一个二维数组
tang_array = np.array([[1,2,3],[4,5,6],[7,8,9]])
tang_array[1,2] = 60
tang_array
array([[ 1,  2,  3],
       [ 4,  5, 60],
       [ 7,  8,  9]])
# 取第二行的全部元素
tang_array[1]
array([ 4,  5, 60])
# 取第三列的全部元素
tang_array[:,2]
array([ 3, 60,  9])
# arange函数创建数组
tang_array = np.arange(0,100,10)
tang_array
array([ 0, 10, 20, 30, 40, 50, 60, 70, 80, 90])
# 创建布尔类型的数组
mask = np.array([0,0,0,1,1,1,0,0,1,1],dtype = bool)
mask
array([False, False, False,  True,  True,  True, False, False,  True,
        True])
tang_array[mask]
array([30, 40, 50, 80, 90])
# 取出索引位置为1的元素
tang_array[mask]
array([30, 40, 50, 80, 90])
# 使用random模块
random_array = np.random.rand(10)
random_array
array([0.90850622, 0.71146276, 0.31891891, 0.220512  , 0.87201367,
       0.36051132, 0.60903653, 0.3308868 , 0.09855745, 0.97485481])
# 判断每一个元素是否符合要求,返回布尔类型
mask = random_array > 0.5
mask
array([ True,  True, False, False,  True, False,  True, False, False,
        True])
# 灵活使用判断条件
tang_array = np.array([10,20,30,40,50])
np.where(tang_array >= 30)
(array([2, 3, 4], dtype=int64),)
# 还可以合并成一句,输出对应索引的元素
tang_array = np.array([10,20,30,40,50])
np.where(tang_array >= 30)
tang_array[np.where(tang_array >= 30)]
array([30, 40, 50])
# 布尔类型的数组还可以直接进行对比
y = np.array([1,0,1,0])
x = np.array([0,1,1,0])
x == y
array([False, False,  True,  True])
# 常用的逻辑判断操作在numpy中页也有实现,比如logical_and与操作,logical_or或操作
print(np.logical_and(x,y))
print(np.logical_or(x,y))
[False False  True False]
[ True  True  True False]

数据类型与数值计算

# 创建数组的时候可以指定其数据类型
tang_array = np.array([1,2,3,4,5],dtype = np.float32)
print(tang_array)
# 观察dtype其属性
print(tang_array.dtype)
[1. 2. 3. 4. 5.]
float32
# numpy中字符串的名字叫为object,python中为str
tang_array = np.array(['1','2','3','4','str'],dtype = np.object)
print(tang_array)
# 观察dtype其属性
print(tang_array.dtype)
['1' '2' '3' '4' 'str']
object
# 可以使用asarray直接对创建好的数组进行类型转换
tang_array = np.array([1,2,3,4,5])
tang_array2 = np.asarray(tang_array,dtype = np.float32)
tang_array2
array([1., 2., 3., 4., 5.], dtype=float32)
# 存在关联的复制
tang_array = np.array([[1,2,3],[4,5,6],[7,8,9]])
tang_array2 = tang_array
print("tang_array:\n",tang_array,"\ntang_array2:\n",tang_array2)
tang_array[1][1] = 100
print("tang_array:\n",tang_array,"\ntang_array2:\n",tang_array2)
tang_array:
 [[1 2 3]
 [4 5 6]
 [7 8 9]] 
tang_array2:
 [[1 2 3]
 [4 5 6]
 [7 8 9]]
tang_array:
 [[  1   2   3]
 [  4 100   6]
 [  7   8   9]] 
tang_array2:
 [[  1   2   3]
 [  4 100   6]
 [  7   8   9]]

可以看见,对其中的一个进行改动,两个都会进行改动,说明这两个变量根本上是一样的

# 不存在关联的复制
tang_array = np.array([[1,2,3],[4,5,6],[7,8,9]])
tang_array2 = tang_array.copy()
print("tang_array:\n",tang_array,"\ntang_array2:\n",tang_array2)
tang_array[1][1] = 100
print("tang_array:\n",tang_array,"\ntang_array2:\n",tang_array2)
tang_array:
 [[1 2 3]
 [4 5 6]
 [7 8 9]] 
tang_array2:
 [[1 2 3]
 [4 5 6]
 [7 8 9]]
tang_array:
 [[  1   2   3]
 [  4 100   6]
 [  7   8   9]] 
tang_array2:
 [[1 2 3]
 [4 5 6]
 [7 8 9]]

此时改变其中一个数组的某个变量,另外的一个数组将维持不变,所以这两个就不存在关联了

Numpy计算操作

# 定义操作的二维数组
tang_array = np.array([[1,2,3],[4,5,6]])
print(tang_array)
[[1 2 3]
 [4 5 6]]
tang_array = np.array([[1,2,3],[4,5,6]])
print(tang_array)
# 对整组元素进行求和
print("np.sum(tang_array):",np.sum(tang_array))
# 对二维数组进行对列求和
print("np.sum(tang_array,axis=0):",np.sum(tang_array,axis=0))
# 对二维数组进行对行求和
print("np.sum(tang_array,axis=1):",np.sum(tang_array,axis=1))
[[1 2 3]
 [4 5 6]]
np.sum(tang_array): 21
np.sum(tang_array,axis=0): [5 7 9]
np.sum(tang_array,axis=1): [ 6 15]
tang_array = np.array([[1,2,3],[4,5,6]])
print(tang_array)
# 各元素累乘
print("tang_array.prod():",tang_array.prod())
# 对二维数组进行对列累乘
print("tang_array.prod(axis = 0):",tang_array.prod(axis = 0))
# 对二维数组进行对行累乘
print("tang_array.prod(axis = 1):",tang_array.prod(axis = 1))
[[1 2 3]
 [4 5 6]]
tang_array.prod(): 720
tang_array.prod(axis = 0): [ 4 10 18]
tang_array.prod(axis = 1): [  6 120]
tang_array = np.array([[1,2,3],[4,5,6]])
print(tang_array)
# 求元素中的最小值
print("tang_array.min():",tang_array.min())
# 对二维数组进行对列求最小值
print("tang_array.min(axis =  0):",tang_array.min(axis =  0))
# 对二维数组进行对行求最小值
print("tang_array.min(axis =  1):",tang_array.min(axis =  1))
[[1 2 3]
 [4 5 6]]
tang_array.min(): 1
tang_array.min(axis =  0): [1 2 3]
tang_array.min(axis =  1): [1 4]
tang_array = np.array([[1,2,3],[4,5,6]])
print(tang_array)
# 求元素中的平均值
print("tang_array.mean():",tang_array.mean())
# 对二维数组进行对列求平均值
print("tang_array.mean(axis =  0):",tang_array.mean(axis =  0))
# 对二维数组进行对行求平均值
print("tang_array.mean(axis =  1):",tang_array.mean(axis =  1))
[[1 2 3]
 [4 5 6]]
tang_array.mean(): 3.5
tang_array.mean(axis =  0): [2.5 3.5 4.5]
tang_array.mean(axis =  1): [2. 5.]
tang_array = np.array([[1,2,3],[4,5,6]])
print(tang_array)
# 求元素中的标准差
print("tang_array.std():",tang_array.std())
# 对二维数组进行对列求标准差
print("tang_array.std(axis =  0):",tang_array.std(axis =  0))
# 对二维数组进行对行求标准差
print("tang_array.std(axis =  1):",tang_array.std(axis =  1))
[[1 2 3]
 [4 5 6]]
tang_array.std(): 1.707825127659933
tang_array.std(axis =  0): [1.5 1.5 1.5]
tang_array.std(axis =  1): [0.81649658 0.81649658]
tang_array = np.array([[1,2,3],[4,5,6]])
print(tang_array)
# 求元素中的方差
print("tang_array.var():",tang_array.var())
# 对二维数组进行对列求方差
print("tang_array.var(axis =  0):",tang_array.var(axis =  0))
# 对二维数组进行对行求方差
print("tang_array.var(axis =  1):",tang_array.var(axis =  1))
[[1 2 3]
 [4 5 6]]
tang_array.var(): 2.9166666666666665
tang_array.var(axis =  0): [2.25 2.25 2.25]
tang_array.var(axis =  1): [0.66666667 0.66666667]
# 比2小的全部为2,比4大的全部为4
tang_array.clip(2,4)
array([[2, 2, 3],
       [4, 4, 4]])
# 4舍5入函数round,可以利用参数decimals来实现指定精度
tang_array = np.array([1.3621,4.1415,2.633])
print(tang_array.round())
print(tang_array.round(decimals = 1))
print(tang_array.round(decimals = 2))
[1. 4. 3.]
[1.4 4.1 2.6]
[1.36 4.14 2.63]
# 得到索引的位置
print(tang_array.argmin(axis = 0))
print(tang_array.argmax())
0
1

矩阵乘法

1.第一种是按照对应的位置元素进行相乘

2.第二种是在数组中进行矩阵乘法

x = np.array([5,5])
y = np.array([2,2])
# 第一种:对应位置乘法
np.multiply(x,y)
array([10, 10])
# 第二种:矩阵乘法
np.dot(x,y)
20

以上结果是 52 + 52 = 20而来

x.shape = 2,1
x
array([[5],
       [5]])
np.dot(x,y)
---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-182-6849a5f7ad6c> in <module>
----> 1 np.dot(x,y)


<__array_function__ internals> in dot(*args, **kwargs)


ValueError: shapes (2,1) and (2,) not aligned: 1 (dim 1) != 2 (dim 0)

这说明矩阵乘法必须是确定对应的维度的相同的

y.shape = 1,2
y
array([[2, 2]])
np.dot(x,y)
array([[10, 10],
       [10, 10]])
np.dot(y,x)
array([[20]])

矩阵相乘要注意顺序,顺序不一样,结果一般都不一样,还要注意数组的维度和个数

排序操作

# 对整个数组进行排序
tang_array = np.array([[1,5,3],[4,2,6]])
print(tang_array)
np.sort(tang_array)
[[1 5 3]
 [4 2 6]]





array([[1, 3, 5],
       [2, 4, 6]])
# 对数组进行列排序
tang_array = np.array([[1,5,3],[4,2,6]])
print(tang_array)
print(np.sort(tang_array,axis = 0))  # 列排序
print(np.sort(tang_array,axis = 1))  # 行排序,默认为1
[[1 5 3]
 [4 2 6]]
[[1 2 3]
 [4 5 6]]
[[1 3 5]
 [2 4 6]]
np.argsort(tang_array)
array([[0, 2, 1],
       [1, 0, 2]], dtype=int64)

其中0表示最小的元素,也就是位于第一个的元素;1表示第二小的元素,也就是位于第二个元素,以此类推

而1,5,3中最小的是1,第二小的是3,所以1的下标为0,3的下标为1,5的下标为2,因此转换结果为1,5,3–>0,2,1; 4,2,6–>1,0,2

# linspace(0,10,10)函数表示在0-10之间产生等间隔的10个数
tang_array = np.linspace(0,10,10)
tang_array
array([ 0.        ,  1.11111111,  2.22222222,  3.33333333,  4.44444444,
        5.55555556,  6.66666667,  7.77777778,  8.88888889, 10.        ])
# 显示合适的位置插入
values = np.array([2.5,6.5,9.5])
np.searchsorted(tang_array,values)
array([3, 6, 9], dtype=int64)



对于 np.lexsort( [ 1*tang_array[:,1] ])

其中的 1 表示升序; 若是是 -1 则表示降序

而[:,1]表示 按列来指引排序, 1表示按照的是第2列,若是0则表为第一列

# 按照第二列升序
tang_array = np.array([[1,0,6],[1,7,0],[2,3,1],[2,4,0]])
print(tang_array)
# 其中的 1 表示升序; 若是是 -1 则表示降序
index = np.lexsort([1*tang_array[:,1]])
tang_array[index]
[[1 0 6]
 [1 7 0]
 [2 3 1]
 [2 4 0]]





array([[1, 0, 6],
       [2, 3, 1],
       [2, 4, 0],
       [1, 7, 0]])
# 按照第三列倒序
tang_array = np.array([[1,0,6],[1,7,0],[2,3,1],[2,4,0]])
print(tang_array)
# 其中的 1 表示升序; 若是是 -1 则表示降序
index = np.lexsort([-1*tang_array[:,2]])
tang_array[index]
[[1 0 6]
 [1 7 0]
 [2 3 1]
 [2 4 0]]





array([[1, 0, 6],
       [2, 3, 1],
       [1, 7, 0],
       [2, 4, 0]])

数组形状操作

tang_array = np.arange(10)
tang_array
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
tang_array.shape
(10,)
tang_array.shape = 2,5
tang_array
array([[0, 1, 2, 3, 4],
       [5, 6, 7, 8, 9]])
# 再增加一个维度
tang_array = tang_array[np.newaxis,:]
tang_array.shape
(1, 2, 5)
tang_array.shape = 5,2
tang_array
array([[0, 1],
       [2, 3],
       [4, 5],
       [6, 7],
       [8, 9]])
# 再增加一个维度
tang_array = tang_array[np.newaxis,:]
tang_array.shape
(1, 5, 2)
# 去掉多余的维度
tang_array = tang_array.squeeze()
print(tang_array)
[[0 1]
 [2 3]
 [4 5]
 [6 7]
 [8 9]]
[[0 1]
 [2 3]
 [4 5]
 [6 7]
 [8 9]]
# 装置的操作
tang_array = tang_array.transpose()
tang_array
array([[0, 2, 4, 6, 8],
       [1, 3, 5, 7, 9]])
tang_array = tang_array.T
tang_array
array([[0, 2, 4, 6, 8],
       [1, 3, 5, 7, 9]])

直接执行变量名字就相当于打印操作,但是如果对变量计算或者处理操作时一定需要指定一个新的变量名,否则相当于只是打印而没有执行具体的操作

数组的拼接

a = np.array([[1,2,3],[4,5,6]])
b = np.array([[7,8,9],[10,11,12]])
#本来是二维数组,拼接之后还是二维数组
np.concatenate((a,b)) # 注意此处是两个括号,因为(a,b)是一个参数
array([[ 1,  2,  3],
       [ 4,  5,  6],
       [ 7,  8,  9],
       [10, 11, 12]])
#本来是二维数组,拼接之后还是二维数组
np.concatenate((a,b),axis = 1)
array([[ 1,  2,  3,  7,  8,  9],
       [ 4,  5,  6, 10, 11, 12]])

本来是二维数组,拼接之后还是二维数组,在拼接的方向上,维度必须一致

d = np.array([1,2,3])
e = np.array([4,5,6])
np.stack((d,e))
array([[1, 2, 3],
       [4, 5, 6]])
np.hstack((d,e))
array([1, 2, 3, 4, 5, 6])
np.vstack((d,e))
array([[1, 2, 3],
       [4, 5, 6]])

hstack是水平拼接,vstack是垂直拼接

#对于多维数组,不仅仅可以拼接,还可以拉平
print("a:\n",a)
print("\na.flatten:\n",a.flatten())
a:
 [[1 2 3]
 [4 5 6]]

a.flatten:
 [1 2 3 4 5 6]

创建数组函数

# 范围是2-20,步长为2
np.arange(2,20,2)
array([ 2,  4,  6,  8, 10, 12, 14, 16, 18])
# 使用log函数创建数组
np.logspace(0,1,5)
array([ 1.        ,  1.77827941,  3.16227766,  5.62341325, 10.        ])
# 快速创建行向量
np.r_[0:5:1]
array([0, 1, 2, 3, 4])
# 快速创建列向量
np.c_[0:5:1]
array([[0],
       [1],
       [2],
       [3],
       [4]])
# 创建一维零矩阵或者是单位矩阵
print("np.zeros(3):",np.zeros(3))
print("np.ones(3):",np.ones(3))
np.zeros(3): [0. 0. 0.]
np.ones(3): [1. 1. 1.]
# 创建二维零矩阵或者是单位矩阵
print("np.zeros((3,3)):\n",np.zeros((3,3)))
print("\nnp.ones((3,3)):\n",np.ones((3,3)))
np.zeros((3,3)):
 [[0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]]

np.ones((3,3)):
 [[1. 1. 1.]
 [1. 1. 1.]
 [1. 1. 1.]]
# 创建单位矩阵E
print("np.identity(3):\n",np.identity(3))
np.identity(3):
 [[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]

生成任意数值的数组一般有两种方法:

1.创建空数组并指定其大小,然后再往里面填充

2.先创建好一个数组,再初始化一个零矩阵让其和某一个数组的维度上一致

# 方法1:创建空数组再填充
a = np.empty(6)
a.fill(2)
a
array([2., 2., 2., 2., 2., 2.])
# 方法2:先创建好一个数组,再初始化一个零矩阵让其和某一个数组的维度上一致
tang_array = np.array([1,2,3,4,5,6,7,8,9])
np.zeros_like(tang_array)
array([0, 0, 0, 0, 0, 0, 0, 0, 0])

随机模块

# 随机构建一个3x2的矩阵
np.random.rand(3,2)
array([[0.63287675, 0.67865303],
       [0.51197231, 0.21019408],
       [0.51085968, 0.24048343]])
# 随机构建一个5x4的矩阵,并且数值取值为0-10之间
np.random.randint(10,size = (5,4))
array([[9, 6, 6, 1],
       [9, 2, 2, 2],
       [1, 3, 9, 9],
       [8, 1, 7, 7],
       [8, 0, 4, 3]])
# 随机构建一个一维数组,数值取值为10-100
np.random.randint(10,100,10)
array([82, 47, 67, 19, 79, 60, 18, 42, 54, 35])
# 只想返回一个随机数
np.random.rand()
0.6771646568850656
# 还可以指定分布以及所需参数来进行随机,eg:高斯分布中的μ和Σ
# np.random.normal(mu,sigma,10)
#一下设置为均值为0,标准差为0.1的高斯分布随机数
np.random.normal(0,0.1,10)
array([-0.12494684, -0.11084639, -0.12966329, -0.03182122, -0.06762391,
       -0.00908411,  0.07992548, -0.11843161, -0.01535346,  0.12912371])
#可以控制输出结果,设置精度
np.set_printoptions(precision = 2)
np.random.normal(0,0.1,10)
array([ 0.03,  0.04, -0.02,  0.02, -0.04, -0.01,  0.08, -0.09,  0.14,
        0.09])
# 每次的执行结果均不一样
tang_array = np.arange(10)
np.random.shuffle(tang_array)
tang_array
array([4, 5, 6, 9, 2, 0, 3, 8, 7, 1])
# 设置随机种子
np.random.seed(10)
np.random.normal(0,0.1,10)
array([ 0.13,  0.07, -0.15, -0.  ,  0.06, -0.07,  0.03,  0.01,  0.  ,
       -0.02])

numpy的文件读写操作

%%writefile Clichong.txt
1 2 3 4 5 6
6 5 4 3 2 1
Overwriting Clichong.txt

注意:以上的魔法指令可以在本地创建出这样的一个文件,但是%%writefile Clichong.txt要位于第一行,否则会报错UsageError: Line magic function %%writefile not found.而且注意不要加注释,否则会连同注释一起写进文档里面
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Rmkr7jqZ-1611072500951)(attachment:image.png)]

# numpy中一行就可以完成数据的读取, 如果是使用python来实现文档读取可以查看博客:https://blog.csdn.net/weixin_44751294/article/details/109732684
data = np.loadtxt("Clichong.txt")
print("data:\n",data)
[[1. 2. 3. 4. 5. 6.]
 [6. 5. 4. 3. 2. 1.]]
%%writefile Clichong.txt
1,2,3,4,5,6
6,5,4,3,2,1
Overwriting Clichong.txt
#读取的时候还可以指定好分隔符
data = np.loadtxt('Clichong.txt',delimiter = ',')
print("data:\n",data)
data:
 [[1. 2. 3. 4. 5. 6.]
 [6. 5. 4. 3. 2. 1.]]
%%writefile Clichong.txt
x,y,a,f,w,f
1,2,3,4,5,6
6,5,4,3,2,1
Overwriting Clichong.txt
# 读取的时候还可以删除无关项
data = np.loadtxt('Clichong.txt',delimiter = ',',skiprows = 1)
print("data:\n",data)
data:
 [[1. 2. 3. 4. 5. 6.]
 [6. 5. 4. 3. 2. 1.]]
# 将数据写入文件中
tang_array = np.array([1,2,3,4,5,6,7,8,9,0])
np.savetxt('Lawrence.txt',tang_array,fmt = '%d',delimiter = ',')
# .npy也就是ndarray格式,可以将程序运行结果保存起来。例如可以将建立机器学习模型求得的参数保存成".npy"格式,再次使用的时候直接加载就行。
# 这样就可以存储好内存中的中间结果
tang_array = np.array([[1,2,3],[4,5,6]])
# 把结果保存为npy格式
np.save('tang_array.npy',tang_array)
# 读取之前保存的结果,依旧是Numpy的数组格式
np.load('tang_array.npy')
array([[1, 2, 3],
       [4, 5, 6]])
# np.loadtxt()函数的API文档,以下语句可以打印出来
print(help(np.loadtxt))

Help on function loadtxt in module numpy:

loadtxt(fname, dtype=<class ‘float’>, comments=’#’, delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0, encoding=‘bytes’, max_rows=None)
Load data from a text file.

Each row in the text file must have the same number of values.

Parameters
----------
fname : file, str, or pathlib.Path
    File, filename, or generator to read.  If the filename extension is
    ``.gz`` or ``.bz2``, the file is first decompressed. Note that
    generators should return byte strings.
dtype : data-type, optional
    Data-type of the resulting array; default: float.  If this is a
    structured data-type, the resulting array will be 1-dimensional, and
    each row will be interpreted as an element of the array.  In this
    case, the number of columns used must match the number of fields in
    the data-type.
comments : str or sequence of str, optional
    The characters or list of characters used to indicate the start of a
    comment. None implies no comments. For backwards compatibility, byte
    strings will be decoded as 'latin1'. The default is '#'.
delimiter : str, optional
    The string used to separate values. For backwards compatibility, byte
    strings will be decoded as 'latin1'. The default is whitespace.
converters : dict, optional
    A dictionary mapping column number to a function that will parse the
    column string into the desired value.  E.g., if column 0 is a date
    string: ``converters = {0: datestr2num}``.  Converters can also be
    used to provide a default value for missing data (but see also
    `genfromtxt`): ``converters = {3: lambda s: float(s.strip() or 0)}``.
    Default: None.
skiprows : int, optional
    Skip the first `skiprows` lines, including comments; default: 0.
usecols : int or sequence, optional
    Which columns to read, with 0 being the first. For example,
    ``usecols = (1,4,5)`` will extract the 2nd, 5th and 6th columns.
    The default, None, results in all columns being read.

    .. versionchanged:: 1.11.0
        When a single column has to be read it is possible to use
        an integer instead of a tuple. E.g ``usecols = 3`` reads the
        fourth column the same way as ``usecols = (3,)`` would.
unpack : bool, optional
    If True, the returned array is transposed, so that arguments may be
    unpacked using ``x, y, z = loadtxt(...)``.  When used with a structured
    data-type, arrays are returned for each field.  Default is False.
ndmin : int, optional
    The returned array will have at least `ndmin` dimensions.
    Otherwise mono-dimensional axes will be squeezed.
    Legal values: 0 (default), 1 or 2.

    .. versionadded:: 1.6.0
encoding : str, optional
    Encoding used to decode the inputfile. Does not apply to input streams.
    The special value 'bytes' enables backward compatibility workarounds
    that ensures you receive byte arrays as results if possible and passes
    'latin1' encoded strings to converters. Override this value to receive
    unicode arrays and pass strings as input to converters.  If set to None
    the system default is used. The default value is 'bytes'.

    .. versionadded:: 1.14.0
max_rows : int, optional
    Read `max_rows` lines of content after `skiprows` lines. The default
    is to read all the lines.

    .. versionadded:: 1.16.0

Returns
-------
out : ndarray
    Data read from the text file.

See Also
--------
load, fromstring, fromregex
genfromtxt : Load data with missing values handled as specified.
scipy.io.loadmat : reads MATLAB data files

Notes
-----
This function aims to be a fast reader for simply formatted files.  The
`genfromtxt` function provides more sophisticated handling of, e.g.,
lines with missing values.

.. versionadded:: 1.10.0

The strings produced by the Python float.hex method can be used as
input for floats.

Examples
--------
>>> from io import StringIO   # StringIO behaves like a file object
>>> c = StringIO(u"0 1\n2 3")
>>> np.loadtxt(c)
array([[0., 1.],
       [2., 3.]])

>>> d = StringIO(u"M 21 72\nF 35 58")
>>> np.loadtxt(d, dtype={'names': ('gender', 'age', 'weight'),
...                      'formats': ('S1', 'i4', 'f4')})
array([(b'M', 21, 72.), (b'F', 35, 58.)],
      dtype=[('gender', 'S1'), ('age', '<i4'), ('weight', '<f4')])

>>> c = StringIO(u"1,0,2\n3,0,4")
>>> x, y = np.loadtxt(c, delimiter=',', usecols=(0, 2), unpack=True)
>>> x
array([1., 3.])
>>> y
array([2., 4.])

None

猜你喜欢

转载自blog.csdn.net/weixin_44751294/article/details/112855524