【大数据技术能力提升_2】numpy学习

numpy学习

标签(空格分隔): numpy python


数据类型

5种类型:布尔值(bool),整数(int),无符号整数(uint)、浮点(float)、复数(complex)

支持的原始类型与 C 中的原始类型紧密相关:

Numpy 的类型 C 的类型 描述
np.bool bool 存储为字节的布尔值(True或False)
np.byte signed char 平台定义
np.ubyte unsigned char 平台定义
np.short short 平台定义
np.ushort unsigned short 平台定义
np.intc int 平台定义
np.uintc unsigned int 平台定义
np.int_ long 平台定义
np.uint unsigned long 平台定义
np.longlong long long 平台定义
np.ulonglong unsigned long long 平台定义
np.half / np.float16 - 半精度浮点数:符号位,5位指数,10位尾数
np.single float 平台定义的单精度浮点数:通常为符号位,8位指数,23位尾数
np.double double 平台定义的双精度浮点数:通常为符号位,11位指数,52位尾数。
np.longdouble long double
np.csingle float complex 复数,由两个单精度浮点数(实部和虚部)表示
np.cdouble double complex 复数,由两个双精度浮点数(实部和虚部)表示。
np.clongdouble long double complex 复数,由两个扩展精度浮点数(实部和虚部)表示。

由于其中许多都具有依赖于平台的定义,因此提供了一组固定大小的别名:

注:类型代码一般是头一个字母+位数/8,如complex256位c32

|Numpy 的类型 |C 的类型 |类型代码|描述|
| :----------- | :------: || :--- |
|np.int8 |int8_t |i1|字节(-128到127)|
|np.int16 |int16_t |i2|整数(-32768至32767)|
|np.int32 |int32_t |i4|整数(-2147483648至2147483647)|
|np.int64 |int64_t |i8|整数(-9223372036854775808至9223372036854775807)|
|np.uint8 |uint8_t |u1|无符号整数(0到255)|
|np.uint16 |uint16_t |u2|无符号整数(0到65535)|
|np.uint32 |uint32_t |u4|无符号整数(0到4294967295)|
|np.uint64 ||uint64_t |u8|无符号整数(0到18446744073709551615)||
|np.intp |intptr_t |无|用于索引的整数,通常与索引相同 ssize_t|
|np.uintp |uintptr_t |无|整数大到足以容纳指针|
|np.float32 |float |f或f4|8位指数 |
|np.float64 / np.float_ |double |f8|请注意,这与内置python float的精度相匹配。|
|np.complex64 |float complex |c8|复数,由两个32位浮点数(实数和虚数组件)表示|
|np.complex128 / np.complex_ |double complex |c16| 请注意,这与内置python 复合体的精度相匹配。|

创建、操作narray

import numpy as np
#新版本
x1 = np.int8([0,1,2,3,4,5,6,7,8,9]) 
x2 = np.arange(10, dtype=np.int8)
x1, x2
(array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=int8),
 array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=int8))
#老版本
y1 = np.array(np.arange(9), dtype=np.int8)
y2 = np.array(np.arange(9), dtype='i1')
y1, y2
"""
新手最容易犯的一个错误就是把数组内容直接当做参数传给array,如np.array(1,2,3)
"""
'
xe6x96xb0xe6x89x8bxe6x9cx80xe5xaexb9xe6x98x93xe7x8axafxe7x9ax84xe4xb8x80xe4xb8xaaxe9x94x99xe8xafxafxe5xb0xb1xe6x98xafxe6x8ax8axe6x95xb0xe7xbbx84xe5x86x85xe5xaexb9xe7x9bxb4xe6x8exa5xe5xbdx93xe5x81x9axe5x8fx82xe6x95xb0xe4xbcxa0xe7xbbx99arrayxefxbcx8cxe5xa6x82np.array(1,2,3)
'
#要转换数组的类型,请使用 .astype() 方法(首选)或类型本身作为函数
x1.astype('u1'), x2.astype(int),np.int16(y1), np.uint16(y2)
(array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=uint8),
 array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
 array([0, 1, 2, 3, 4, 5, 6, 7, 8], dtype=int16),
 array([0, 1, 2, 3, 4, 5, 6, 7, 8], dtype=uint16))
#dtype属性,代表数组的类型;shape属性,代表数组的形状;ndim属性,代表数组有几个维度
#size属性:代表数组中元素的个数, itemsize属性:代表数组中单个元素以字节计的大小
#data属性:数组中实际的数据
z = np.arange(15).reshape((3,5))
z.shape, z.dtype, z.ndim, z.size, z.itemsize, z.data, np.issubdtype(z.dtype, np.integer), np.issubdtype(z.dtype, np.floating)
((3L, 5L),
 dtype('int32'),
 2,
 15,
 4,
 <read-write buffer for 0x0000000007485580, size 60, offset 0 at 0x000000000745BC38>,
 True,
 False)

溢出错误

当值需要比数据类型中的可用内存更多的内存时,例如,numpy.power对于64位整数正确计算 100 * 10 * 8,但对于32位整数给出1874919424(不正确)。

np.power(100, 8, dtype=np.int64), np.power(100, 8, dtype=np.int32)
(10000000000000000, 1874919424)
# NumPy分别提供numpy.iinfo 并numpy.finfo 验证NumPy整数和浮点值的最小值或最大值:
np.iinfo(np.int), np.iinfo(np.int32), np.iinfo(np.int64)
(iinfo(min=-2147483648, max=2147483647, dtype=int32),
 iinfo(min=-2147483648, max=2147483647, dtype=int32),
 iinfo(min=-9223372036854775808, max=9223372036854775807, dtype=int64))

创建数组有5种常规机制:

1、从其他Python结构(例如,列表,元组)转换
2、numpy原生数组的创建(例如,arange、ones、zeros等)
3、从磁盘读取数组,无论是标准格式还是自定义格式
4、通过使用字符串或缓冲区从原始字节创建数组
5、使用特殊库函数(例如,random)

Ones 和 zeros 填充方式

注:[,]里面是可选参数,如:empty(shape[, dtype, order]) ,shape是必选参数,dtype, order是可选参数

方法 描述
empty(shape[, dtype, order]) 返回给定形状和类型的新数组,而无需初始化条目。
empty_like(prototype[, dtype, order, subok, …]) 返回形状和类型与给定数组相同的新数组。
eye(N[, M, k, dtype, order]) 返回一个二维数组,对角线上有一个,其他地方为零。
identity(n[, dtype]) 返回标识数组。
ones(shape[, dtype, order]) 返回给定形状和类型的新数组,并填充为1。
ones_like(a[, dtype, order, subok, shape]) 返回形状与类型与给定数组相同的数组。
zeros(shape[, dtype, order]) 返回给定形状和类型的新数组,并用零填充。
zeros_like(a[, dtype, order, subok, shape]) 返回形状与类型与给定数组相同的零数组。
full(shape, fill_value[, dtype, order]) 返回给定形状和类型的新数组,并用fill_value填充。
full_like(a, fill_value[, dtype, order, …]) 返回形状和类型与给定数组相同的完整数组。

从现有的数据创建

方法 描述
array(object[, dtype, copy, order, subok, ndmin]) 创建一个数组。
asarray(a[, dtype, order]) 将输入转换为数组。
asanyarray(a[, dtype, order]) 将输入转换为ndarray,但通过ndarray子类。
ascontiguousarray(a[, dtype]) 返回内存中的连续数组(ndim > = 1)(C顺序)。
asmatrix(data[, dtype]) 将输入解释为矩阵。
copy(a[, order]) 返回给定对象的数组副本。
frombuffer(buffer[, dtype, count, offset]) 将缓冲区解释为一维数组。
fromfile(file[, dtype, count, sep, offset]) 根据文本或二进制文件中的数据构造一个数组。
fromfunction(function, shape, **kwargs) 通过在每个坐标上执行一个函数来构造一个数组。
fromiter(iterable, dtype[, count])
fromstring(string[, dtype, count, sep]) 从字符串中的文本数据初始化的新一维数组。
loadtxt(fname[, dtype, comments, delimiter, …]) 从文本文件加载数据。

注:可通过np.array?来查看相关函数的说明

#zero和ones代码实现
"""
zero:创建所有元素为0的数组
ones:创建所有元素为1的数组
empty:创建所有元素为随机的数组 *****
"""
np.empty([2, 2], dtype=int), np.empty((3, 3)),np.empty_like(([1,2,3], [4,5,6])),np.eye(4)
(array([[43998544,        0],
        [62099504,        0]]), array([[0.22222222, 0.44444444, 0.66666667],
        [0.88888889, 1.11111111, 1.33333333],
        [1.55555556, 1.77777778, 2.        ]]), array([[         0, 1073741824,          0],
        [1074790400,          0, 1075314688]]), array([[1., 0., 0., 0.],
        [0., 1., 0., 0.],
        [0., 0., 1., 0.],
        [0., 0., 0., 1.]]))
#因为浮点数的有限精度问题,array返回的数组可能无法预知,因此出现浮点数时,最好用linspace
np.arange(10,100,10),np.linspace(0,2,10)
(array([10, 20, 30, 40, 50, 60, 70, 80, 90]),
 array([0.        , 0.22222222, 0.44444444, 0.66666667, 0.88888889,
        1.11111111, 1.33333333, 1.55555556, 1.77777778, 2.        ]))

打印数组

打印出来非常类似嵌套列表
如果数组太长,则会自动忽略部数据,只打印首位
print np.arange(24).reshape(2,3,4),np.arange(1000000)
[[[ 0  1  2  3]
  [ 4  5  6  7]
  [ 8  9 10 11]]

 [[12 13 14 15]
  [16 17 18 19]
  [20 21 22 23]]] [     0      1      2 ... 999997 999998 999999]

基本操作

在数组上进行算术操作都是元素级别的(elementwise)。

注:在线性代数中,乘号*代表的矩阵乘法,但在numpy中代表元素级别乘法,矩阵乘法用np.dot(a,b)或a.dot(b)

若a+=b,a是int,b是float,则会报错,因为b比a更精错,但b+=a则不会报错

a = np.array([1,2,3,4])
b = np.arange(4)
a-b, a+b, a*b, a*2, a/3,a.dot(b) #全部新增的一个数组
(array([1, 1, 1, 1]),
 array([1, 3, 5, 7]),
 array([ 0,  2,  6, 12]),
 array([2, 4, 6, 8]),
 array([0, 0, 1, 1]),
 20)

ndarray内置函数:sum,min,max,comsum,并且可以通过制定axis=0或1来指定对行或者列操作

通用函数

一元ufunc

函数 说明
abs、fabs 计算整数、浮点数或复数的绝对值。对于非复数,fabs更快
sqrt 计算各元素的平方根
square 计算各元素的平方
exp 计算各元素的指数(e^X)
log、log10、log2、log1P 分别对自然对数((e^X)),底数分别为e、10、2、1+x
sign 计算各元素的正负号:1(正数)、-1(负数)
floor 计算各元素小于等于该值的最大整数
ceil 计算各元素大于等于该值的最小整数
rint 将各元素四舍五入到最接近的整数,保留dtype
modf 将数组的小数与整数部分分别以两个独立的数组形式返回
isnan 返回哪些值是nan的布尔型数组
isfinite、isinf 返回哪些数组是有穷或无穷的布尔型数组
cos、cosh、sin、sinh、tan、tanh 普通和双曲三角函数
arccos、arccosh、arcsin、arcsinh、arctan、arctanh 反三角函数
logical_not 计算各元素not x的真值。相当于-arr

二元ufunc

函数 说明
add 将数组中对应的元素相加
subtract 从第一个数组中减去第二个数组中的元素
multiply 数组元素相乘
divide、floor_divide 除法或除不要余数
power 第一个元素A,根据第二个相应的元素计算(A^B)
maximum、fmax、minimum、fmin 元素最大值和最小值计算。fmax和fmin将忽略NaN
mod 除法求余数
copysign 将第二个数组中的符号复制给第一个数组中的值
greater、greater_equal、less、less_equal、equal、not_equal 比较运算,产生布尔型数组。依次> >= < <= == !=
logical_and、logical_or、logical_xor 真值逻辑运算。与或非

索引、切片以及遍历

一维数组非常类似与python的list和tuple,它们可以被index、slice、iterate
copy方法可以复制数组和标量值

c = np.arange(10)
c,c[0],c[1:3],c[:5],c[5:],c[:-1],c[:]
(array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
 0,
 array([1, 2]),
 array([0, 1, 2, 3, 4]),
 array([5, 6, 7, 8, 9]),
 array([0, 1, 2, 3, 4, 5, 6, 7, 8]),
 array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))

跟列表最重要的区别在于,数组的切片的数据不会复制,任何修改都会反馈到元数据上

c1 = c[4:6]
c1[:] = 111
c
array([  0,   1,   2,   3, 111, 111,   6,   7,   8,   9])
#二维数组的索引和切片
d = np.arange(16).reshape((4,4))
d[1][0],d[0,1]
(4, 1)
#布尔型索引
#布尔型索引在多维数组里面经常会跟上面的数字索引方法混用
e = np.array(['a','b','c','e','f','g','h','i','j','k'])
e == 'e',c[e == 'f'],c[e != 'e'],c[(e == 'f')|(e != 'f')]
(array([False, False, False,  True, False, False, False, False, False,
        False]),
 array([111]),
 array([  0,   1,   2, 111, 111,   6,   7,   8,   9]),
 array([  0,   1,   2,   3, 111, 111,   6,   7,   8,   9]))

元素的形状

可以通过reshape(创建新数组)、resize(改变原数组)、ravel(使数组变扁平)

将不同的数组堆叠(stacking)起来

多个数组可以沿着不同的额轴堆叠起来,用vstack(竖向)、hstack(横向)

将一个数组切分成多个

使用hsplit或vsplit将一个数组沿制定方向切分split(array,(x,y))切分为x列和y列,split(array,n)切分为n个数组

拷贝与视图

1、简单的赋值不发生拷贝;函数调用也不会产生拷贝
2、不同数据对象可以共享相同的数据,view方法新建一个数组,但是仍使用相同的数据
3、深拷贝:copy

广播

在NumPy中如果遇到大小不一致的数组运算,就会触发广播机制。满足一定的条件才能触发广播,不然也会报错。

形状相同

形状相同的数组之间的运算就是在对应位做运算。

形状不同

当数组大小不一致时,就会触发广播机制。广播机制的规则:

1.让所有输入数组都向其中shape最长的数组看齐,shape中不足的部分都通过在前面加1补齐;

2.输出数组的shape是输入数组shape的各个轴上的最大值;

3.如果输入数组的某个轴和输出数组的对应轴的长度相同或者其长度为1时,这个数组能够用来计算,否则出错;

4.当输入数组的某个轴的长度为1时,沿着此轴运算时都用此轴上的第一组值。
原文地址:https://www.cnblogs.com/CQ-LQJ/p/11832508.html