Numpy(科学计算库)---讲解

Numpy(科学计算库)---讲解,第1张

本内容来自《跟着迪哥学Python数据分析与机器学习实战》,该篇博客将其内容进行了整理,加上了自己的理解,所做小笔记。若有侵权,联系立删。
迪哥说以下的许多函数方法都不用死记硬背,多查API多看文档,确实,跟着迪哥混就完事了~~~
Numpy官网API

以下代码段均在Jupyter Notebook下进行运行 *** 作
每天过一遍,腾讯阿里明天见~

一、 基本 *** 作 Ⅰ,array数组

导包

import numpy as np#导包,起个别名np

常规方法对列表中的每一个元素都+1,在python中是不可行的

array = [1,2,2,3]
array + 1
"""
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
 in 
      1 array = [7,8,7,0,8,4,9,3,4]
----> 2 array + 1

TypeError: can only concatenate list (not "int") to list
"""
#输出结果显示此处创建的是一个list结构,无法执行上述 *** 作。

在Numpy中可以使用array()函数创建数组,从而实现对每个元素都+1 *** 作

array = np.array([1,2,2,3])
array + 1
"""
array([2, 3, 3, 4])
"""
print(type(array))
"""

"""
#输出结果显示数据类型是ndarray,也就是Numpy中的底层数据类型,后续要进行各种矩阵 *** 作的基本对象就是它。

在Numpy中 如果对数组执行一个四则运算,就相当于要对其中每一元素做相同的 *** 作。

#arrar---[1,2,2,3]
arr = array + 1
arr
"""
array([2, 3, 3, 4])
"""
#arrar---[1,2,2,3]
#arr---[2,3,3,4]
arr + array
"""
array([3, 5, 5, 7])
"""
#arrar---[1,2,2,3]
#arr---[2,3,3,4]
arr * array
"""
array([ 2,  6,  6, 12])
"""
Ⅱ,数组特性
array
"""
array([1, 2, 2, 3])
"""
array.shape
"""
(4,)
"""
#表示当前为一维,其中有4个元素
two_arr = np.array([[1,2,3],[2,3,4]])
two_arr
"""
array([[1, 2, 3],
       [2, 3, 4]])
"""
two_arr.shape
"""
(2, 3)
"""
#表示当前为2行3列

在使用ndarray数组时,数组中的所有元素必须是同一类型的,若不是同一类型,数组元素会自动地向下进行转换。
int→float→str

yy = np.array([1,3,4,5])
yy
"""
array([1, 3, 4, 5])
"""

str>int

yy = np.array([1,3,4,'5'])
yy
"""
array(['1', '3', '4', '5'], dtype='

float>int

yy = np.array([1,3,4,5.0])
yy
"""
array([1., 3., 4., 5.])
"""

str>float

yy = np.array(['1',3.0,4.0,5.0])
yy
"""
array(['1', '3.0', '4.0', '5.0'], dtype='
Ⅲ,数组属性 *** 作
two_arr
"""
array([[1, 2, 3],
       [2, 3, 4]])
"""

当前数据格式

type(two_arr)
"""
numpy.ndarray
"""

当前数据类型

two_arr.dtype
"""
dtype('int32')
"""

当前数组中的元素个数

two_arr.size
"""
6
"""

当前数据维度

two_arr.ndim
"""
2
"""
二、索引与切片 Ⅰ,数值索引
array
"""
array([1, 2, 2, 3])
"""

下标从0开始,左闭右开[1,3)

array[1:3]
"""
array([2, 2])
"""

负数表示从倒数开始取数据,如[–2:]表示从数组中倒数第二个数据开始取到最后。

array[-2:]
"""
array([2, 3])
"""

索引 *** 作在二维数据中也是同理

two_arr
"""
array([[1, 2, 3],
       [2, 3, 4]])
"""

下标从0开始,左上角为(0,0),第1行,第2列

two_arr[1,2]
"""
4
"""

可以基于索引位置进行赋值 *** 作,前行后列,通过逗号隔开,[行,列]

two_arr[1,1] = 9
two_arr
"""
array([[1, 2, 3],
       [2, 9, 4]])
"""

下标从0开始,取第1行数据

two_arr[1]
"""
array([2, 9, 4])
"""

下标从0开始,取最后一列数据

two_arr[:,-1]
"""
array([3, 4])
"""

下标从0开始,取第一列数据

two_arr[:,0]
"""
array([1, 2])
"""
Ⅱ,bool索引

arange(0,100,10)表示从0开始到100,每隔10个数取一个元素

beyond = np.arange(0,100,10)
beyond
"""
array([ 0, 10, 20, 30, 40, 50, 60, 70, 80, 90])
"""
mask = np.array([0,0,1,1,0,0,1,1,1,0],dtype=bool)
mask#0为False,1为True
"""
array([False, False,  True,  True, False, False,  True,  True,  True,
       False])
"""
beyond[mask]#通过mask作为索引(True)来找beyond中的数据
"""
array([20, 30, 60, 70, 80])
"""

rand(10)表示在[0,1)区间上随机选择10个数

random_arr = np.random.rand(10)
random_arr
"""
array([0.22612583, 0.69781025, 0.1703525 , 0.07685978, 0.38899791,
       0.75130758, 0.3418809 , 0.68655566, 0.43836518, 0.14533855])
"""
#判断其中每一个元素是否满足要求,返回布尔类型。
mask = random_arr > 0.5
mask
"""
array([False,  True, False, False, False,  True, False,  True, False,
       False])
"""
#找到符合要求的索引位置
yy_array = np.array([10,20,30,20,40,60])
np.where(yy_array > 20)
"""
(array([2, 4, 5], dtype=int64),)
"""
#按照满足要求的索引来选择元素
yy_array[np.where(yy_array > 20)]
"""
array([30, 40, 60])
"""
#可以对不同的数组进行对比
x = np.array([1,4,7,8,5,2])
y = np.array([1,4,7,2,5,8])
x == y
"""
array([ True,  True,  True, False,  True, False])
"""
#逻辑与
np.logical_and(x,y)
"""
array([ True,  True,  True,  True,  True,  True])
"""
#逻辑或
np.logical_or(x,y)
"""
array([ True,  True,  True,  True,  True,  True])
"""
三、数据类型与数值计算 Ⅰ,数据类型
yy_arr = np.array([1,2,3,4],dtype=np.float32)
yy_arr
"""
array([1., 2., 3., 4.], dtype=float32)
"""
yy_arr.dtype
"""
dtype('float32')
"""

在Numpy中字符串的名字叫object

yy_arr = np.array(['1','1.1','beyond'],dtype=np.object)
yy_arr
"""
array(['1', '1.1', 'beyond'], dtype=object)
"""

对创建好的数组进行类型转换

yy_arr = np.array([1,2,3,4])
yy_arr1 = np.asarray(yy_arr,dtype=np.float32)
yy_arr1
"""
array([1., 2., 3., 4.], dtype=float32)
"""
Ⅱ,复制与赋值

若用=来对两个数组赋值的话,如果对其中一个变量进行 *** 作,另一变量的结果也跟着发生变化,说明它们根本就是一样的,只不过用两个不同的名字表示罢了。

array_o = np.array([[1,3,1],[2,3,1],[2,1,3]])
array_o
"""
array([[1, 3, 1],
       [2, 3, 1],
       [2, 1, 3]])
"""
array_n = array_o
array_n
"""
array([[1, 3, 1],
       [2, 3, 1],
       [2, 1, 3]])
"""
array_n[1,1] = 666
array_n
"""
array([[  1,   3,   1],
       [  2, 666,   1],
       [  2,   1,   3]])
"""
array_o
"""
array([[  1,   3,   1],
       [  2, 666,   1],
       [  2,   1,   3]])
"""

如果想让赋值后的变量与之前的变量无关,需要通过复制 *** 作。
此时改变其中一个数组的某个变量,另一个数组依旧保持不变,说明它们不仅名字不一样,而且也根本不是同一件事。

array_y = array_o.copy()
array_o
"""
array([[  1,   3,   1],
       [  2, 666,   1],
       [  2,   1,   3]])
"""
array_y
"""
array([[  1,   3,   1],
       [  2, 666,   1],
       [  2,   1,   3]])
"""
array_y[0,0] = 1014
array_y
"""
array([[1014,    3,    1],
       [   2,  666,    1],
       [   2,    1,    3]])
"""
array_o
"""
array([[  1,   3,   1],
       [  2, 666,   1],
       [  2,   1,   3]])
"""
Ⅲ,数值运算

对数组中所有元素进行求和

yy_arr = np.array([[1,2,1],[2,1,1,],[3,2,2],[1,1,1]])
np.sum(yy_arr)
"""
18
"""

对一个二维数组来说,既可以对列求和,也可以按行求和
指定axis参数表示可以按照第几个维度来进行计算
0为列维度、1为行维度

np.sum(yy_arr,axis=0)
"""
array([7, 6, 5])
"""
np.sum(yy_arr,axis=1)
"""
array([4, 4, 7, 3])
"""
yy_arr
"""
array([[1, 2, 1],
       [2, 1, 1],
       [3, 2, 2],
       [1, 1, 1]])
"""

数组中所有元素进行累乘

yy_arr.prod()
"""
48
"""

数组中各列元素进行累乘

yy_arr.prod(axis=0)
"""
array([6, 4, 2])
"""

数组中各行元素进行累乘

yy_arr.prod(axis=1)
"""
array([ 2,  2, 12,  1])
"""

找数组中所有元素的最小值

yy_arr.min()
"""
1
"""

找数组中所有元素的最小值的索引

yy_arr.argmin()
"""
0
"""

找数组中每一列中元素的最小值

yy_arr.min(axis=0)
"""
array([1, 1, 1])
"""

找数组中每一列中元素的最小值的索引

yy_arr.argmin(axis=0)
"""
array([0, 1, 0], dtype=int64)
"""

找数组中每一行中元素的最小值

yy_arr.min(axis=1)
"""
array([1, 1, 2, 1])
"""

找数组中每一行中元素的最小值的索引

yy_arr.argmin(axis=1)
"""
array([0, 1, 1, 0], dtype=int64)
"""

求所有元素的均值

yy_arr.mean()
"""
1.5
"""

求每列元素的各自均值

yy_arr.mean(axis=0)
"""
array([1.75, 1.5 , 1.25])
"""

求每行元素的各自均值

yy_arr.mean(axis=1)
"""
array([1.33333333, 1.33333333, 2.33333333, 1.        ])
"""

求所有元素的标准差

yy_arr.std()
"""
0.6454972243679028
"""

求每列元素的标准差

yy_arr.std(axis=0)
"""
array([0.8291562, 0.5      , 0.4330127])
"""

求每行元素的标准差

yy_arr.std(axis=1)
"""
array([0.47140452, 0.47140452, 0.47140452, 0.        ])
"""

求所有元素的方差

yy_arr.var()
"""
0.4166666666666667
"""

求每列元素的方差

yy_arr.var(axis=0)
"""
array([0.6875, 0.25  , 0.1875])
"""

求每行元素的方差

yy_arr.var(axis=1)
"""
array([0.22222222, 0.22222222, 0.22222222, 0.        ])
"""

比1小的全部赋值为1,比2大的全部赋值为2

yy_arr.clip(1,2)
"""
array([[1, 2, 1],
       [2, 1, 1],
       [2, 2, 2],
       [1, 1, 1]])
"""

对数组中的元素四舍五入

yy_arr = np.array([1.26,3.45,4.52])
yy_arr.round()
"""
array([1., 3., 5.])
"""

指定一个精度(2位小数)四舍五入

yy_arr.round(decimals=2)
"""
array([1.26, 3.45, 4.52])
"""
Ⅳ,矩阵乘法
x = np.array([2,2])
y = np.array([3,3])

对应位置元素进行相乘

np.multiply(x,y)
"""
array([6, 6])
"""

在数组中进行矩阵乘法

np.dot(x,y)
"""
12
"""
np.dot(y,x)
"""
12
"""

很显然,若是一维数组的话,multiply就是各元素对应相乘,最后的结果还是一维数组;dot就是各元素对应相乘再相加是一个数

接下来看下二维数组的情况,基本常识,行列数需要满足前行乘后列原则

x.shape = 2,1
x
"""
array([[2],
       [2]])
"""
y.shape = 1,2
y
"""
array([[3, 3]])
"""
np.dot(x,y)
"""
array([[6, 6],
       [6, 6]])
"""
np.dot(y,x)
"""
array([[12]])
"""
四、常用功能模块 Ⅰ,排序 *** 作
beyond_arr = np.array([[1.2,2.3,0.5],[1.5,1.9,2.2],[4.2,1.9,6.6],[9.5,10.0,14.1]])
beyond_arr
"""
array([[ 1.2,  2.3,  0.5],
       [ 1.5,  1.9,  2.2],
       [ 4.2,  1.9,  6.6],
       [ 9.5, 10. , 14.1]])
"""

默认按行进行排序,以元素值进行显示

np.sort(beyond_arr)
"""
array([[ 0.5,  1.2,  2.3],
       [ 1.5,  1.9,  2.2],
       [ 1.9,  4.2,  6.6],
       [ 9.5, 10. , 14.1]])
"""

默认按行进行排序,以元素值所对应的索引进行显示

np.argsort(beyond_arr)
"""
array([[2, 0, 1],
       [0, 1, 2],
       [1, 0, 2],
       [0, 1, 2]], dtype=int64)
"""

指定按列进行排序,以元素值进行显示

np.sort(beyond_arr,axis=0)
"""
array([[ 1.2,  1.9,  0.5],
       [ 1.5,  1.9,  2.2],
       [ 4.2,  2.3,  6.6],
       [ 9.5, 10. , 14.1]])
"""

指定按列进行排序,以元素值所对应的索引进行显示

np.argsort(beyond_arr,axis=0)
"""
array([[0, 1, 0],
       [1, 2, 1],
       [2, 0, 2],
       [3, 3, 3]], dtype=int64)
"""

linspace(0,10,10)函数表示在0~10之间产生等间隔的10个数

yy_arr = np.linspace(0,10,10)
yy_arr
"""
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(yy_arr,values)#算出合适的插入位置
"""
array([3, 6, 9], dtype=int64)
"""

将数据按照第一列的升序或者降序对整体数据进行排序:
按照第一列进行降序

yy_arr = np.array([[9,6,3],[2,8,5],[7,4,1],[10,55,42]])
yy_arr
"""
array([[ 9,  6,  3],
       [ 2,  8,  5],
       [ 7,  4,  1],
       [10, 55, 42]])
"""
index = np.lexsort([-1*yy_arr[:,0]])
index
"""
array([3, 0, 2, 1], dtype=int64)
"""
#得到按照第一列进行降序后的索引
#将索引传入原数组中
yy_arr[index]
"""
array([[10, 55, 42],
       [ 9,  6,  3],
       [ 7,  4,  1],
       [ 2,  8,  5]])
"""

按照第一列进行升序

yy_arr
"""
array([[ 9,  6,  3],
       [ 2,  8,  5],
       [ 7,  4,  1],
       [10, 55, 42]])
"""
index = np.lexsort([yy_arr[:,0]])
index
"""
array([1, 2, 0, 3], dtype=int64)
"""
#得到按照第一列进行升序后的索引
#将索引传入原数组中
yy_arr[index]
"""
array([[ 2,  8,  5],
       [ 7,  4,  1],
       [ 9,  6,  3],
       [10, 55, 42]])
"""
Ⅱ,数组形状 *** 作
beyond_arr = np.arange(10)
beyond_arr
"""
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
"""
beyond_arr.shape
"""
(10,)
"""
#一维

可以通过shape属性来改变数组形状,前提是变换前后元素个数必须保持一致。

beyond_arr.shape = 2,5
beyond_arr
"""
array([[0, 1, 2, 3, 4],
       [5, 6, 7, 8, 9]])
"""
#二维 2行5列

当创建一个数组之后,还可以给它增加一个维度

yy = np.arange(10)
yy
"""
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
"""
yy.shape
"""
(10,)
"""
#一维
yy = yy[np.newaxis,:]
yy
"""
array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])
"""
yy.shape
"""
(1, 10)
"""
#二维 1行10列

也可以对数组进行压缩 *** 作,把多余的维度去掉

yy = yy.squeeze()
yy
"""
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
"""
yy.shape
"""
(10,)
"""
#一维

还可以对数组进行转置 *** 作

beyond = np.array([[1,2,4,5],[9,6,3,2],[7,5,6,3]])
beyond
"""
array([[1, 2, 4, 5],
       [9, 6, 3, 2],
       [7, 5, 6, 3]])
"""

方法一:

beyond.transpose()
"""
array([[1, 9, 7],
       [2, 6, 5],
       [4, 3, 6],
       [5, 2, 3]])
"""

方法二:

beyond.T
"""
array([[1, 9, 7],
       [2, 6, 5],
       [4, 3, 6],
       [5, 2, 3]])
"""
Ⅲ,数组的拼接

可以通过拼接将两份数据组合到一起
concatenate函数用于把数据拼接在一起,注意:原来a、b都是二维的,拼接后的结果也是二维的,相当于在原来的维度上进行拼接,默认axis=0,也可以指定拼接维度。

a = np.array([[2,4,1],[4,5,3]])
b = np.array([[7,4,1],[4,5,6]])
np.concatenate((a,b))
"""
array([[2, 4, 1],
       [4, 5, 3],
       [7, 4, 1],
       [4, 5, 6]])
"""
np.concatenate((a,b),axis=1)
"""
array([[2, 4, 1, 7, 4, 1],
       [4, 5, 3, 4, 5, 6]])
"""

还有另一种拼接方法
原始数据都是一维的,但是拼接后是二维的,相当于新创建一个维度。

a1 = np.array([7,8,9])
b1 = np.array([9,6,3])
a1.shape
"""
(3,)
"""
#一维
b1.shape
"""
(3,)
"""
#一维
np.stack((a1,b1))
"""
array([[7, 8, 9],
       [9, 6, 3]])
"""
#拼接之后就变成了二维了

类似还有hstack和vstack *** 作,分别表示水平和竖直的拼接方式。

np.hstack((a1,b1))
"""
array([7, 8, 9, 9, 6, 3])
"""
np.vstack((a1,b1))
"""
array([[7, 8, 9],
       [9, 6, 3]])
"""

在数据维度等于1时,它们的作用相当于stack,用于创建新轴。
在维度大于或等于2时,它们的作用相当于cancatenate,用于在已有轴上进行 *** 作。

np.hstack((a,b))
"""
array([[2, 4, 1, 7, 4, 1],
       [4, 5, 3, 4, 5, 6]])
"""
np.vstack((a,b))
"""
array([[2, 4, 1],
       [4, 5, 3],
       [7, 4, 1],
       [4, 5, 6]])
"""

对于多维数组,还可以将其拉平

a
"""
array([[2, 4, 1],
       [4, 5, 3]])
"""
a.flatten()
"""
array([2, 4, 1, 4, 5, 3])
"""
Ⅳ,创建数组函数

np.arange()可以自己定义数组的取值区间以及取值间隔,这里表示在[2,20)区间上每隔2个数值取一个元素

np.arange(2,20,2)
"""
array([ 2,  4,  6,  8, 10, 12, 14, 16, 18])
"""

对数函数默认以10为底,[0,1)平均取5个数,取对数

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]])
"""

创建零矩阵,里面包括3个元素

np.zeros(3)
"""
array([0., 0., 0.])
"""

创建3×3的零矩阵

np.zeros((3,3))
"""
array([[0., 0., 0.],
       [0., 0., 0.],
       [0., 0., 0.]])
"""

创建3×3的单位矩阵

np.ones((3,3))
"""
array([[1., 1., 1.],
       [1., 1., 1.],
       [1., 1., 1.]])
"""

想生成任意数值的数组,可以根据需求来进行变换

np.ones((3,3))*8
"""
array([[8., 8., 8.],
       [8., 8., 8.],
       [8., 8., 8.]])
"""

指定一个空的,指定好其大小,之后再往里面进行填充

a = np.empty(6)
a
"""
array([0., 0., 0., 0., 0., 0.])
"""

全部填充为1

a.fill(1)
a
"""
array([1., 1., 1., 1., 1., 1.])
"""

创建一个数组,初始化一个零矩阵,让它和某个数组的维度一致

yy = np.array([5,22,10,14])
np.zeros_like(yy)
"""
array([0, 0, 0, 0])
"""

只有对角线有数值,并且为1,也就是创建指定维度的单位矩阵

np.identity(5)
"""
array([[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.]])
"""
Ⅴ,随机模块

随机生成3行2列的数组

np.random.rand(3,2)
"""
array([[0.0321769 , 0.58387082],
       [0.49930902, 0.77043111],
       [0.52521361, 0.54218806]])
"""

返回区间[0,10)之间的随机整数

np.random.randint(10,size=(5,4))
"""
array([[1, 8, 6, 7],
       [1, 8, 4, 5],
       [9, 3, 1, 4],
       [2, 2, 4, 7],
       [1, 7, 5, 2]])
"""

只返回一个随机值

np.random.rand()
"""
0.9361433744193344
"""

指定区间并选择随机数的个数

np.random.randint(0,10,3)
"""
array([3, 9, 7])
"""

指定分布类型,以及所需参数来随机生成随机数初始化
例如高斯分布,均值为0,标准差为0.1

np.random.normal(0,0.1,10)
"""
array([-1.97e-01, -8.71e-02, -1.11e-01,  2.75e-02, -3.64e-02, -1.17e-01,
       -1.34e-01,  1.45e-01,  1.17e-04, -1.19e-03])
"""

返回的结果中小数点后面的位数实在太多了,指定返回结果的小数位数

np.set_printoptions(precision=2)
np.random.normal(0,0.1,10)
"""
array([ 0.07, -0.12, -0.06, -0.06, -0.13, -0.06,  0.02, -0.1 ,  0.03,
       -0.15])
"""

数据一般都是按照采集顺序排列的,但是在机器学习中很多算法都要求数据之间相互独立,所以需要先对数据集进行洗牌 *** 作:

sq = np.arange(10)
sq
"""
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
"""
np.random.shuffle(sq)
sq
"""
array([4, 1, 0, 7, 2, 6, 3, 9, 8, 5])
"""

很容易发现当数据集变化时,参数也发生变化
有些时候希望进行随机 *** 作,但却要求每次的随机结果都相同
此时就需要指定随机种子
这里每次都把种子设置成10,说明随机策略相同,无论执行多少次随机 *** 作,其结果都是相同的
我的理解就是,随机种子的不同表示随机表的不同,有很多随机表,看你用哪一个,不同的随机种子对应不同的随机表

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])
"""
Ⅵ,文件读写

Notebook的魔法指令,相当于写了一个beyond.txt文件

%%writefile beyond.txt
1 2 3 7 8 9
5 6 9 1 4 7
"""
Writing beyond.txt
"""

data = np.loadtxt('beyond.txt')
data
"""
array([[1., 2., 3., 7., 8., 9.],
       [5., 6., 9., 1., 4., 7.]])
"""

数据中带有分隔符

%%writefile beyond1.txt
1,2,3,7,8,9
5,6,9,1,4,7
"""
Writing beyond1.txt
"""

#读取数据的时候也需要提前指定好分隔符
data = np.loadtxt('beyond1.txt',delimiter=',')
data
"""
array([[1., 2., 3., 7., 8., 9.],
       [5., 6., 9., 1., 4., 7.]])
"""

多加入一列描述,可以把它当作无关项

%%writefile beyond2.txt
q,w,e,r,t,y
1,2,3,7,8,9
5,6,9,1,4,7
"""
Writing beyond2.txt
"""

#读取数据的时候可以去掉前几行,直接从第1行开始读取
data = np.loadtxt('beyond2.txt',delimiter=',',skiprows=1)
data
"""
array([[1., 2., 3., 7., 8., 9.],
       [5., 6., 9., 1., 4., 7.]])
"""

可以通过help来查看帮助文档

print(help(np.loadtxt))
"""
Help on function loadtxt in module numpy:

loadtxt(fname, dtype=, comments='#', delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0, encoding='bytes', max_rows=None, *, like=None)
    Load data from a text file.
    
    Each row in the text file must have the same number of values.
    
    Parameters
    ----------
    fname : file, str, pathlib.Path, list of str, generator
        File, filename, list, or generator to read.  If the filename
        extension is ``.gz`` or ``.bz2``, the file is first decompressed. Note
        that generators must return bytes or strings. The strings
        in a list or produced by a generator are treated as lines.
    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
    like : array_like
        Reference object to allow the creation of arrays which are not
        NumPy arrays. If an array-like passed in as ``like`` supports
        the ``__array_function__`` protocol, the result will be defined
        by it. In this case, it ensures the creation of an array object
        compatible with that passed in via this argument.
    
        .. versionadded:: 1.20.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("0 1\n2 3")
    >>> np.loadtxt(c)
    array([[0., 1.],
           [2., 3.]])
    
    >>> d = StringIO("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', '>> c = StringIO("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.])
    
    This example shows how `converters` can be used to convert a field
    with a trailing minus sign into a negative number.
    
    >>> s = StringIO('10.01 31.25-\n19.22 64.31\n17.57- 63.94')
    >>> def conv(fld):
    ...     return -float(fld[:-1]) if fld.endswith(b'-') else float(fld)
    ...
    >>> np.loadtxt(s, converters={0: conv, 1: conv})
    array([[ 10.01, -31.25],
           [ 19.22,  64.31],
           [-17.57,  63.94]])

None
"""

Numpy工具包不仅可以读取数据,而且可以将数据写入文件中

#把结果保存为npy格式
beyond = np.array([[1,4,7,8],[5,2,3,6]])
np.save('yy.npy',beyond,)

#读取之前保存的结果,依旧是Numpy数组格式
np.load('yy.npy')
"""
array([[1, 4, 7, 8],
       [5, 2, 3, 6]])
"""

俺迪哥说了,在数据处理过程中,中间的结果都保存在内存中,如果关闭Notebook或者重启IDE,再次使用的时候就要从头再来,十分耗时。如果能将中间结果保存下来,下次直接读取处理后的结果就非常高效,保存成“.npy”格式的方法非常实用。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/langs/868354.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-13
下一篇 2022-05-13

发表评论

登录后才能评论

评论列表(0条)

保存