2020年10月NumPy学习

it2023-06-13  87

# numpy基础学习

基础numpy基础学习1.常量1.1numpy.nan 1.2numpy.inf1.3numpy.pinumpy.e 2数据类型2.1 常见数据类型2.2创建数据类型2.3数据类型信息 3时间日期和时间增量3.1datetime64基础3.2datetime64和timedelta64运算3.3datetime64的应用 4数组的创建4.1依据现有数据来创建ndarray通过array()函数进行创建通过asarray()函数进行创建通过ffion()函数进行创建 依据ones和zeros填充零数组1数组空数组单位数组对角数组常数数组 利用数值范围来创建ndarray结构数组的创建利用字典来定义结构利用包含多个元组的里表来定义结构 5数组的属性6副本与视图

基础

numpy基础学习

1.常量

import numpy as np#导入Numpy库

1.1numpy.nan

nan、NaN、NAN三种方式都可以表示空值:np.nan,np.NaN,np.NAN

## 两个numpy.nan是不想等的 print(np.nan == np.nan) print(np.nan != np.nan) False True np.isnan(np.nan)#判断是否nan函数,返回布尔值 x=np.array([1,1,8,np.nan,10]) print(x) #[ 1. 1. 8. nan 10.] y=np.isnan(x) print(y) #[False False False True False] z=np.count_nonzero(y)#因为python中False==0,所以此函数返回1 print(z) #1 [ 1. 1. 8. nan 10.] [False False False True False] 1

删除nan所在行

x=np.arange(0,25).reshape(5,5) x=np.array(x,dtype=float) x[2,3]=np.nan x[0,4]=np.nan print(x) [[ 0. 1. 2. 3. nan] [ 5. 6. 7. 8. 9.] [10. 11. 12. nan 14.] [15. 16. 17. 18. 19.] [20. 21. 22. 23. 24.]] np.where(np.isnan(x)) #将数组中nan元素的所在索引保存为tuple,第一个元素是行号,第二个元素是列号 (array([0, 2]), array([4, 3])) np.delete(x,np.where(np.isnan(x))[0],axis=0)#删除nan所在行 array([[ 5., 6., 7., 8., 9.], [15., 16., 17., 18., 19.], [20., 21., 22., 23., 24.]])

1.2numpy.inf

Inf、inf、infty、Infinity、PINF都可以表示正无穷

1.3numpy.pi

np.pi 3.141592653589793

numpy.e

np.e 2.718281828459045

2数据类型

2.1 常见数据类型

Python原生的数据类型较少:

数值类型 int 整形float 浮点型complex 复数bool 布尔值 序列对象 str 字符串list 列表tuple 元组 键值对 set 集合dict 字典

这在不需要关心数据在计算机中表示的所有方式的应用中是方便的。然而,对于科学计算,通常需要更多的控制。为了加以区分 numpy 在这些类型名称末尾都加了“_”

下表列出了常用的numpy数据类型

类型备注说明bool_=bool88位布尔类型int8=byte8位整型int16=short16位整型int32=intc32位整型int_=int64=long=int()=intp64位整型uint8=ubyte8位无符号整型uint16=ushort16位无符号整型uint32=uintc32位无符号整型uint64=uintp=uint()=uint64位无符号整形float16=half16位浮点型float32=single32位浮点型float_=float64=double64位浮点型str_=unicode_=str()=unicodeUnicode字符串datetime64日期时间类型timedelta64表示两个时间之间的间隔

2.2创建数据类型

numpy的数据类型实际上是dtype对象的实例,描述了如何解释与数组项对应的固定大小的内存块中的字节。 它描述了数据的以下几个方面:

数据类型(整型、浮点型、Python对象等)。数据的大小(例如整数中有多少字节)。数据的顺序(little-endian 或 big-endian)。如果数据类型是结构化数据类型,则是其他数据类型的集合(例如,描述由整数和浮点数组成的数组项)。 结构的 “字段” 的名称是什么,通过这些名称可以访问它们。每个 字段 的数据类型是什么,以及每个字段占用内存块的哪一部分。 如果数据类型是子数组,那么它的形状和数据类型是什么。 每个内建类型都有一个唯一定义它的字符代码: 字符对应类型备注bboolean‘b1’isigned integer‘i1’,‘i2’,‘i4’,‘i8’uunsigned integer‘u1’,‘u2’,‘u4’,‘u8’ffloating-point‘f2’,‘f4’,‘f8’ccomplex floating-pointmtimedelta64表示两个时间之间的间隔Mdatetime64日期时间类型Oobjects(byte-)strings3表示长度为3的字符串UUnicodeUnicode字符串Vvoid a=np.dtype('b1') print(a.type) print(a.itemsize)#np.itemsize,ndarray 对象中每个元素的大小,以字节为单位 print('--'*20) a=np.dtype('i1') print(a.type) print(a.itemsize) print('--'*20) a = np.dtype('i2') print(a.type) print(a.itemsize) print('--'*20) a=np.dtype('i4') print(a.type) print(a.itemsize) print('--'*20) a=np.dtype('i8') print(a.type) print(a.itemsize) print('--'*20) a=np.dtype('u1') print(a.type) print(a.itemsize) print('--'*20) a=np.dtype('u2') print(a.type) print(a.itemsize) print('--'*20) a=np.dtype('u4') print(a.type) print(a.itemsize) print('--'*20) a=np.dtype('u8') print(a.type) print(a.itemsize) print('--'*20) a=np.dtype('f2') print(a.type) print(a.itemsize) print('--'*20) a=np.dtype('f4') print(a.type) print(a.itemsize) print('--'*20) a=np.dtype('f8') print(a.type) print(a.itemsize) print('--'*20) a=np.dtype('S') print(a.type) print(a.itemsize) print('--'*20) a=np.dtype('S3') print(a.type) print(a.itemsize) print('--'*20) a=np.dtype('U3') print(a.type) print(a.itemsize) print('--'*20) <class 'numpy.bool_'> 1 ---------------------------------------- <class 'numpy.int8'> 1 ---------------------------------------- <class 'numpy.int16'> 2 ---------------------------------------- <class 'numpy.int32'> 4 ---------------------------------------- <class 'numpy.int64'> 8 ---------------------------------------- <class 'numpy.uint8'> 1 ---------------------------------------- <class 'numpy.uint16'> 2 ---------------------------------------- <class 'numpy.uint32'> 4 ---------------------------------------- <class 'numpy.uint64'> 8 ---------------------------------------- <class 'numpy.float16'> 2 ---------------------------------------- <class 'numpy.float32'> 4 ---------------------------------------- <class 'numpy.float64'> 8 ---------------------------------------- <class 'numpy.bytes_'> 0 ---------------------------------------- <class 'numpy.bytes_'> 3 ---------------------------------------- <class 'numpy.str_'> 12 ----------------------------------------

2.3数据类型信息

Python的浮点数通常是64位浮点数,几乎等同于np.float64。 NumPy和Python整数类型的行为在整数溢出方面存在这显著差异,与NumPy不同,Python的int是灵活的,也就是说,Python整数可以扩展以容纳任何整数并不会溢出。

#输出整型的范围 ii16=np.iinfo(np.int16) ''' iinfo(type) Machine limits for integer types.整型的上下限 Attributes ---------- bits : int The number of bits occupied by the type.类型占用的位数 min : int The smallest integer expressible by the type.整型可以表达的最小值 max : int The largest integer expressible by the type.整型可以表达的最大值 Parameters ---------- int_type : integer type, dtype, or instance The kind of integer data type to get information about. ''' print(ii16.min) print(ii16.max) print('--'*20) ii32=np.iinfo(np.int32) print(ii32.min) print(ii32.max) print('--'*20) -32768 32767 ---------------------------------------- -2147483648 2147483647 ---------------------------------------- #输出浮点型的范围 ''' finfo(dtype) Machine limits for floating point types. Attributes ---------- bits : int占用位数 The number of bits occupied by the type. eps : float最小可表达的正数 The smallest representable positive number such that ``1.0 + eps != 1.0``. Type of `eps` is an appropriate floating point type. epsneg : floating point number of the appropriate type The smallest representable positive number such that ``1.0 - epsneg != 1.0``. iexp : int The number of bits in the exponent portion of the floating point representation. machar : MachAr The object which calculated these parameters and holds more detailed information. machep : int The exponent that yields `eps`. max : floating point number of the appropriate type The largest representable number. maxexp : int The smallest positive power of the base (2) that causes overflow. min : floating point number of the appropriate type The smallest representable number, typically ``-max``. minexp : int The most negative power of the base (2) consistent with there being no leading 0's in the mantissa. negep : int The exponent that yields `epsneg`. nexp : int The number of bits in the exponent including its sign and bias. nmant : int The number of bits in the mantissa. precision : int The approximate number of decimal digits to which this kind of float is precise. resolution : floating point number of the appropriate type The approximate decimal resolution of this type, i.e., ``10**-precision``. tiny : float The smallest positive usable number. Type of `tiny` is an appropriate floating point type. Parameters ---------- dtype : float, dtype, or instance Kind of floating point data-type about which to get information. ''' ff16=np.finfo(np.float16) print(ff16.bits) print(ff16.min) print(ff16.max) print(ff16.eps) print('--'*20) ff32=np.finfo(np.float32) print(ff32.bits) print(ff32.min) print(ff32.max) print(ff32.eps) 16 -65500.0 65500.0 0.000977 ---------------------------------------- 32 -3.4028235e+38 3.4028235e+38 1.1920929e-07

3时间日期和时间增量

3.1datetime64基础

在NumPy中,我们很方便的将字符串转换为时间日期类型datetime64(datetime已经被python包含的日期时间库占用),datetime64是带单位的日期时间类型,单位如下:

日期单位代码含义时间单位代码含义Y年h小时M月m分钟W周s秒D天ms毫秒--us微秒--ns纳秒--ps皮秒--fs飞秒--as阿托秒

1秒=1000毫秒 1毫秒=100微秒

#从字符串创建datetime64类型时,默认情况下,numpy会根据字符串自动选择对应的单位 a=np.datetime64('2020-03-01') print(a,a.dtype) print('--'*20) a=np.datetime64('2020-03') print(a,a.dtype) print('--'*20) a=np.datetime64('2020-03-01 20:00:05') print(a,a.dtype) print('--'*20) a=np.datetime64('2020-03-01 20:00') print(a,a.dtype) print('--'*20) a=np.datetime64('2020-03-01 20') print(a,a.dtype) print('--'*20) 2020-03-01 datetime64[D] ---------------------------------------- 2020-03 datetime64[M] ---------------------------------------- 2020-03-01T20:00:05 datetime64[s] ---------------------------------------- 2020-03-01T20:00 datetime64[m] ---------------------------------------- 2020-03-01T20 datetime64[h] ---------------------------------------- #从字符串创建datetime64类型时,可以强制指定使用的单位 a=np.datetime64('2020-03','D') print(a,a.dtype) print('--'*20) a=np.datetime64('2020-03','Y') print(a,a.dtype) print('--'*20) print(np.datetime64('2020-03')==np.datetime64('2020-03-01')) print(np.datetime64('2020-03')==np.datetime64('2020-03-02')) ''' 2020-03和2020-03-01是同一个时间 如果两个datetime64对象具有不同的单位,他们可能仍然代表相同的时刻。并且从较大单位 (如月份)转换为较小的单位(如天数)是安全的 ''' 2020-03-01 datetime64[D] ---------------------------------------- 2020 datetime64[Y] ---------------------------------------- True False #从字符串创建datetime64数组时,如果单位不统一,则一律转换为其中最小的单位 a=np.array(['2020-03','2020-03-08','2020-03-08 20:00'],dtype='datetime64') print(a,a.dtype) ['2020-03-01T00:00' '2020-03-08T00:00' '2020-03-08T20:00'] datetime64[m] #使用arange(),创建datetime64数组,用于生成日期范围 a=np.arange('2020-08-01','2020-08-10',dtype=np.datetime64) print(a,a.dtype) print('--'*20) a=np.arange('2020-08-01 20:00','2020-08-10',dtype=np.datetime64) print(a,a.dtype) print('--'*20) a=np.arange('2020-05','2020-12',dtype=np.datetime64) print(a,a.dtype) ['2020-08-01' '2020-08-02' '2020-08-03' '2020-08-04' '2020-08-05' '2020-08-06' '2020-08-07' '2020-08-08' '2020-08-09'] datetime64[D] ---------------------------------------- ['2020-08-01T20:00' '2020-08-01T20:01' '2020-08-01T20:02' ... '2020-08-09T23:57' '2020-08-09T23:58' '2020-08-09T23:59'] datetime64[m] ---------------------------------------- ['2020-05' '2020-06' '2020-07' '2020-08' '2020-09' '2020-10' '2020-11'] datetime64[M]

3.2datetime64和timedelta64运算

timedelta64表示两个datetime64之间的差。timedelta64也是带单位的,并且和相减运算中的两个datetime64中的较小的单位保持一致。

a=np.datetime64('2020-03-08')-np.datetime64('2020-03-07') b=np.datetime64('2020-03-08')-np.datetime64('2020-03-07 08:00') c=np.datetime64('2020-03-08')-np.datetime64('2020-03-07 23:00','D') print(a,a.dtype) print('--'*20) print(b,b.dtype) print('--'*20) print(c,c.dtype) a=np.datetime64('2020-03')+np.timedelta64(20,'D') b=np.datetime64('2020-06-15 00:00')+np.timedelta64(12,'h') print(a,a.dtype) print(b,b.dtype) 1 days timedelta64[D] ---------------------------------------- 960 minutes timedelta64[m] ---------------------------------------- 1 days timedelta64[D] 2020-03-21 datetime64[D] 2020-06-15T12:00 datetime64[m]

生成timedelta64时,要注意年(‘Y’)和月(‘M’),这两个单位无法和其他单位进行运算,因为一年有几天,一月有几个小时?这些都是不确定的

a=np.timedelta64(1,'Y') b=np.timedelta64(a,'M') print(a) print(b) print('--'*20) c=np.timedelta64(1,'h') d=np.timedelta64(c,'m') print(c) print(d) print('--'*20) print(np.timedelta64(a,'D')) print(np.timedelta64(b,'D')) ''' 1 years 12 months ---------------------------------------- 1 hours 60 minutes ---------------------------------------- --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-45-c68833b0d416> in <module> 9 print(d) 10 print('--'*20) ---> 11 print(np.timedelta64(a,'D')) 12 print(np.timedelta64(b,'D')) TypeError: Cannot cast NumPy timedelta64 scalar from metadata [Y] to [D] according to the rule 'same_kind' ''' 1 years 12 months ---------------------------------------- 1 hours 60 minutes ---------------------------------------- --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-45-c68833b0d416> in <module> 9 print(d) 10 print('--'*20) ---> 11 print(np.timedelta64(a,'D')) 12 print(np.timedelta64(b,'D')) TypeError: Cannot cast NumPy timedelta64 scalar from metadata [Y] to [D] according to the rule 'same_kind'

timedelta64的运算

a=np.timedelta64(1,'Y') b=np.timedelta64(6,'M') c=np.timedelta64(1,'W') d=np.timedelta64(1,'D') e=np.timedelta64(10,'D') print(a) # 1 years print(b) # 6 months print(a + b) # 18 months print(a - b) # 6 months print(2 * a) # 2 years print(a / b) # 2.0 print(c / d) # 7.0 print(c % e) # 7 days 1 years 6 months 18 months 6 months 2 years 2.0 7.0 7 days

numpy.datetime64 与 datetime.datetime 互相转换

import datetime dt = datetime.datetime(year=2020,month=6,day=1,hour=20,minute=5,second=30) dt64 = np.datetime64(dt,'s') print(dt64,dt64.dtype) dt2 = dt64.astype(datetime.datetime) print(dt2,type(dt2)) 2020-06-01T20:05:30 datetime64[s] 2020-06-01 20:05:30 <class 'datetime.datetime'> #将制定的偏移量应用于工作日。计算下一个工作日,如果当前日期为非工作日,默认报错,可以指定foward和 #backward规则来避免错误

3.3datetime64的应用

为了允许在只有一周中某些日子有效的上下文中使用日期时间,NumPy包含一组“busday”(工作日)功能。

Numpy.busday_offset(dates,offsets,roll=‘raise’,wenkmask=‘1111100’,holidays=None,busdaycal=None,out=None) 首先根据rool参数的规则调整日期成为一个有效的日期,然后再将偏移量应用到给定的日期去计算有是否为有效的日期dates:输入的日期offset:偏移量roll:处理dates为非有效期日即非工作日的规则: raise:为无效的日期添加例外nat:返回无效日期的Nat(不是一个时间类型)forward、following:后面第一个有效日期backward和preceding:前面的地一个有效日期modifiedfollowing:选择后面一个有效期日除非后面一个日期跨到了下一个月份,当出现跨月现象则要取更前一个有效日期modifiedpreceding:选择前面一个有效期日除非后面一个日期跨到了下一个月份,当出现跨月现象则要取更后一个有效日期 weekmask:一个有七个元素的数组,列表、字符串都可以,用来表示一周七天哪几天是工作日,哪几天是非工作日holidays:非工作日的特殊名单,必须是时间类型busdaycal:指定工作日清单,如果给出这个参数,weekmask和holidays可能都不会给出输出:datetime64类型的数组 a=np.busday_offset('2020-07-10',offsets=1)#2020年7月10日是星期五 print(a) 2020-07-13 a = np.busday_offset('2020-07-11', offsets=1) print(a) #当前日期为非工作日,报错 --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-51-72bcd70d2740> in <module> ----> 1 a = np.busday_offset('2020-07-11', offsets=1) 2 print(a) <__array_function__ internals> in busday_offset(*args, **kwargs) ValueError: Non-business day date in busday_offset a=np.busday_offset('2020-07-11',offsets=0,roll='forward') b=np.busday_offset('2020-07-11',offsets=0,roll='backward') print(a) print(b) a=np.busday_offset('2020-07-11',offsets=1,roll='forward') b=np.busday_offset('2020-07-11',offsets=1,roll='backward') print(a) print(b) 2020-07-13 2020-07-10 2020-07-14 2020-07-13

numpy.is_busday(dates, weekmask=‘1111100’, holidays=None, busdaycal=None, out=None) 返回指定日期是否是工作

a=np.is_busday('2020-07-10') b=np.is_busday('2020-10-20') print(a) print(b) True True

统计一个datetime64[D]数组中的工作日天数

begindates = np.datetime64('2020-07-10') enddates = np.datetime64('2020-07-20') a = np.arange(begindates,enddates,dtype='datetime64') b = np.count_nonzero(np.is_busday(a)) print(a) print(b) ['2020-07-10' '2020-07-11' '2020-07-12' '2020-07-13' '2020-07-14' '2020-07-15' '2020-07-16' '2020-07-17' '2020-07-18' '2020-07-19'] 6 np.busday_count(begindates,enddates)#另外一种方法 6

自定义周掩码,如:1111100代表周一二三四五为工作日周六日为非工作日

a = np.is_busday('2020-07-10',weekmask=[1,1,1,1,1,0,0]) b = np.is_busday('2020-07-10',weekmask='1111001') print(a) print(b) True False

4数组的创建

4.1依据现有数据来创建ndarray

通过array()函数进行创建

#创建一维数组 a = np.array([0,1,2,3,4]) b = np.array((0,1,2,3,4)) print(a,type(a)) print(b,type(b)) [0 1 2 3 4] <class 'numpy.ndarray'> [0 1 2 3 4] <class 'numpy.ndarray'> #创建二维数组 c = np.array([[11,12,13,14,15], [16,17,18,19,20], [21,22,23,24,25], [26,27,28,29,30], [31,32,33,34,35]]) print(c,type(c)) [[11 12 13 14 15] [16 17 18 19 20] [21 22 23 24 25] [26 27 28 29 30] [31 32 33 34 35]] <class 'numpy.ndarray'> #创建三维数组 d = np.array([[(1.5,2,3),(4,5,6)], [(3,2,1),(4,5,6)]]) print(d,type(d)) [[[1.5 2. 3. ] [4. 5. 6. ]] [[3. 2. 1. ] [4. 5. 6. ]]] <class 'numpy.ndarray'>

通过asarray()函数进行创建

array() 和 asarray() 都可以将结构数据转化为 ndarray,但是 array() 和 asarray() 主要区别就是当数据源是ndarray 时, array() 仍 然会 copy 出一个副本,占用新的内存,但不改变 dtype 时 asarray() 不会。

x = [[1,1,1],[1,1,1],[1,1,1]] y = np.array(x) z = np.asarray(x) x[1][2]=2 print(x,type(x)) print(y,type(y)) print(z,type(z)) [[1, 1, 1], [1, 1, 2], [1, 1, 1]] <class 'list'> [[1 1 1] [1 1 1] [1 1 1]] <class 'numpy.ndarray'> [[1 1 1] [1 1 1] [1 1 1]] <class 'numpy.ndarray'> x = np.array([[1, 1, 1], [1, 1, 1], [1, 1, 1]]) y = np.array(x) z = np.asarray(x) w = np.asarray(x, dtype=np.int) x[1][2] = 2 print(x,type(x),x.dtype) print(y,type(y),y.dtype) print(z,type(z),z.dtype) print(w,type(w),w.dtype) [[1 1 1] [1 1 2] [1 1 1]] <class 'numpy.ndarray'> int64 [[1 1 1] [1 1 1] [1 1 1]] <class 'numpy.ndarray'> int64 [[1 1 1] [1 1 2] [1 1 1]] <class 'numpy.ndarray'> int64 [[1 1 1] [1 1 2] [1 1 1]] <class 'numpy.ndarray'> int64

更改为较大的dtype时,其大小必须是array的最后一个axis的总大小(以字节为单位)的除数

x = np.array([[1, 1, 1], [1, 1, 1], [1, 1, 1]]) print(x, x.dtype) x.dtype = np.float

通过ffion()函数进行创建

给函数绘图的时候可能会用到 fromfunction() ,该函数可从函数中创建数

def f(x, y): return 10 * x + y x = np.fromfunction(f, (5, 4), dtype=int) print(x) x = np.fromfunction(lambda i, j: i == j, (3, 3), dtype=int) print(x) x = np.fromfunction(lambda i,j:i+j,(3,3),dtype=int) print(x) [[ 0 1 2 3] [10 11 12 13] [20 21 22 23] [30 31 32 33] [40 41 42 43]] [[ True False False] [False True False] [False False True]] [[0 1 2] [1 2 3] [2 3 4]]

依据ones和zeros填充

在机器学习任务中经常做的一件事就是初始化参数,需要用常数值或者随机值来创建一个固定大小的矩

零数组

zeros()函数:返回给定形状和类型的零数组

zeros_like()函数:返回与给定数组形状和类型相同的零数组

x = np.zeros(5) print(x) x = np.zeros([2,3]) print(x) x = np.array([[1,2,3],[4,5,6]]) y = np.zeros_like(x) print(y) [0. 0. 0. 0. 0.] [[0. 0. 0.] [0. 0. 0.]] [[0 0 0] [0 0 0]]

1数组

ones()函数:返回给定形状和类型的1数组

ones_like()函数:返回与给定数组形状和类型相同的1数组

x = np.ones(5) print(x) x = np.ones([2,3]) print(x) x = np.array([[1,2,3],[4,5,6]]) y = np.ones_like(x) [1. 1. 1. 1. 1.] [[1. 1. 1.] [1. 1. 1.]]

空数组

empty() 函数:返回一个空数组,数组元素为随机数。empty_like 函数:返回与给定数组具有相同形状和类型的新 x = np.empty(5) print(x) x = np.empty((3, 2)) print(x) x = np.array([[1, 2, 3], [4, 5, 6]]) y = np.empty_like(x) print(y) [1. 1. 1. 1. 1.] [[4.9e-324 9.9e-324] [1.5e-323 2.0e-323] [2.5e-323 3.0e-323]] [[1 2 3] [4 5 6]]

单位数组

eye()函数:返回一个对角线上为1,其他地方为零的单位数组identity()函数:返回一个方的单位数组 x = np.eye(4) print(x) x = np.eye(2,3) print(x) x = np.identity(4) print(x) [[1. 0. 0. 0.] [0. 1. 0. 0.] [0. 0. 1. 0.] [0. 0. 0. 1.]] [[1. 0. 0.] [0. 1. 0.]] [[1. 0. 0. 0.] [0. 1. 0. 0.] [0. 0. 1. 0.] [0. 0. 0. 1.]]

对角数组

diag()函数:提取对角线或构造对角数组 x = np.arange(9).reshape((3,3)) print(x) print(np.diag(x)) print(np.diag(x,k=1)) print(np.diag(x,k=-1)) v = [1,3,5,7] x = np.diag(v) print(x) [[0 1 2] [3 4 5] [6 7 8]] [0 4 8] [1 5] [3 7] [[1 0 0 0] [0 3 0 0] [0 0 5 0] [0 0 0 7]]

常数数组

full()函数:返回一个常数数组full_like()函数:返回与给定数组具有相同形状和类型的常数数组 x = np.full((2,),7) print(x) x = np.full(2,7) print(x) x = np.full((2,7),7) print(x) x = np.array([[1,2,3],[4,5,6]]) y = np.full_like(x,7) print(y) [7 7] [7 7] [[7 7 7 7 7 7 7] [7 7 7 7 7 7 7]] [[7 7 7] [7 7 7]]

利用数值范围来创建ndarray

arange()函数:返回给定间隔内的均匀间隔的值linspace()函数:返回指定间隔内的等间隔数字logspace()函数:返回以对数刻度均匀分布的数字numpy.random.random()返回一个由(0,1)之间的随机数组成的数组 x = np.arange(5) print(x) x = np.arange(3,7,2) print(x) x = np.linspace(start=0,stop=2,num=9) print(x) x = np.logspace(0,1,5) print(np.around(x,2))#np.around(a,decimals=0,out=None)返回四舍五入的值,可指定精度, x = np.linspace(start=0,stop=1,num=5) x = [10 ** i for i in x] print(np.around(x,2)) x = np.random.random([2,3]) print(x) [0 1 2 3 4] [3 5] [0. 0.25 0.5 0.75 1. 1.25 1.5 1.75 2. ] [ 1. 1.78 3.16 5.62 10. ] [ 1. 1.78 3.16 5.62 10. ] [[0.26644608 0.83755217 0.07641414] [0.56524928 0.71682622 0.25165122]]

结构数组的创建

结构数组,首先要定义结构,然后利用np.array()来创建数组,其参数dtype为定义的结构

利用字典来定义结构

personType = np.dtype({'names':['name','age','weight'], 'formats':['U30','i8','f8']}) a = np.array([('Liming',24,63.9),('Mike',15,67),('Jan',34,45.8)], dtype=personType) print(a,type(a)) [('Liming', 24, 63.9) ('Mike', 15, 67. ) ('Jan', 34, 45.8)] <class 'numpy.ndarray'>

利用包含多个元组的里表来定义结构

personType = np.dtype([('name','U30'),('age','i8'),('weight','f8')]) a = np.array([('Liming',24,63.9),('Mike',15,67.),('Jan',34,45.8)], dtype=personType) print(a,type(a)) [('Liming', 24, 63.9) ('Mike', 15, 67. ) ('Jan', 34, 45.8)] <class 'numpy.ndarray'> #结构数组的取值方法与一般数组差不多,可以通过下标取得元素 print(a[0]) print(a[-2]) #我们可以使用字段名作为下标获取对应的值 print(a['name']) print(a['age']) print(a['weight']) ('Liming', 24, 63.9) ('Mike', 15, 67.) ['Liming' 'Mike' 'Jan'] [24 15 34] [63.9 67. 45.8]

5数组的属性

numpy.ndarray.ndim 用于返回数组的维数(轴的个数)也称为秩,一维数组的秩为1,二维数组的秩为2numpy.ndarray.shape 表示数组的维度,返回一个元组,这个元组的长度就是维度的数目,即ndim属性(秩)numpy.ndarray.size 数组中所有元素的总量,相当于数组的shape中所有元素的成绩,即矩阵的元素总量为行数与列数的乘积numpy.ndarray.dtype ndarray对象的元素类型numpy.ndarray.itemsize 以字节形式返回数组中每一个元素的大小 import numpy as np a = np.array([1,2,3,4,5]) print("数组的秩为:{}".format(a.ndim)) print("数组的维度为:{}".format(a.shape)) print("数组的元素总量为:{}".format(a.size)) print("数组的元素类型为:{}".format(a.dtype)) print("数组的每一个元素大小的字节数为:{}".format(a.itemsize)) 数组的秩为:1 数组的维度为:(5,) 数组的元素总量为:5 数组的元素类型为:int64 数组的每一个元素大小的字节数为:8 b = np.array([[1,2,3],[4,5,6.0]]) print("数组的秩为:{}".format(b.ndim)) print("数组的维度为:{}".format(b.shape)) print("数组的元素总量为:{}".format(b.size)) print("数组的元素类型为:{}".format(b.dtype)) print("数组的每一个元素大小的字节数为:{}".format(b.itemsize)) 数组的秩为:2 数组的维度为:(2, 3) 数组的元素总量为:6 数组的元素类型为:float64 数组的每一个元素大小的字节数为:8

在ndarray中所有元素必须是同一类型,否则会自动向下转换,int->float->str

a = np.array([1,2,3,4,5]) print(a) b = np.array([1,2,3,4,'5']) print(b) c = np.array([1,2,3,4,5.0]) print(c) [1 2 3 4 5] ['1' '2' '3' '4' '5'] [1. 2. 3. 4. 5.]

6副本与视图

在NumPy中,尤其是在做数组运算或数组操作是,返回结果不是数组的 副本 就是 试图 在NumPy中,所有赋值运算不会为数组和数组中的任何元素创建副本。

numpy.ndarray.copy() 函数创建一个副本。对副本数据进行修改,不会影响到原始数据,它们在物理内存中不是同一个位置 x = np.array([1,2,3,4,5,6,7,8]) y = x y[0] = -1 print(x) print(y) x = np.array([1,2,3,4,5,6,7,8]) y = x.copy() y[0] = -1 print(x) print(y) [-1 2 3 4 5 6 7 8] [-1 2 3 4 5 6 7 8] [1 2 3 4 5 6 7 8] [-1 2 3 4 5 6 7 8]

数组切片操作返回的对象只是原始数组的视图

x = np.array([[11,12,13,14,15], [16,17,18,19,20], [21,22,23,24,25], [26,27,28,29,30], [31,32,33,34,35]]) y = x y[::2,:3:2] = -1 # ::2 代表从头到尾步长为2切片 # :3:2 代表从头到第三个元素步长为2切片 # [::2,:3:2]代表选择1,3,5行,1,3列 print(x) print('--'*5) print(y) [[-1 12 -1 14 15] [16 17 18 19 20] [-1 22 -1 24 25] [26 27 28 29 30] [-1 32 -1 34 35]] ---------- [[-1 12 -1 14 15] [16 17 18 19 20] [-1 22 -1 24 25] [26 27 28 29 30] [-1 32 -1 34 35]] x = np.array([[11,12,13,14,15], [16,17,18,19,20], [21,22,23,24,25], [26,27,28,29,30], [31,32,33,34,35]]) y = x.copy() y[::2,:3:2] = -1 print(x) print('--'*5) print(y) [[11 12 13 14 15] [16 17 18 19 20] [21 22 23 24 25] [26 27 28 29 30] [31 32 33 34 35]] ---------- [[-1 12 -1 14 15] [16 17 18 19 20] [-1 22 -1 24 25] [26 27 28 29 30] [-1 32 -1 34 35]]
最新回复(0)