牛骨文教育服务平台(让学习变的简单)
博文笔记

numpy学习笔记

创建时间:2017-05-26 投稿人: 浏览次数:7826

numpy中定义的最重要的对象就是称其为ndarray的多维数组,它是一组同类型元素的集合,元素可用从零开始的索引来访问。

ndarray中的每个元素在内存中占同样大小,是一个data-type类型的对象,data-type简称为dtype。从ndarray中分离出的任一元素都是Python的标量类型。

ndarray基本创建方法是用Numpy中的数组函数:

numpy.array
numpy.array(object, dtype=None, copy=True, order=None, subok=False, ndim=0)

Example:

a=np.array([[1,2,3],[1,4,2]])
b=np.array([1,2,3],dtype=complex)   

Numpy支持的数值类型比Python还多,列出Numpy中不同的标量数据类型:
+ bool_
+ int_
+ intc
+ intp
+ int8
+ int16
+ int32
+ int64
+ uint8
+ uint16
+ uint32
+ uint64
+ float_
+ float16
+ float32
+ float64
+ complex_
+ complex64
+ complex128

使用时:np.bool_, np.float32

numpy.dtype(object, align, copy)

Example:

dt=np.dtype(np.int32)
dt=np.dtype("i4")
dt=np.dtype(">i4")
dt=np.dtype([("age", np.int8)])

备注:’i1’–int8, ‘i2’–int16, ‘i4’–int32, ‘i8’–int64

Example:

dt=np.dtype([("age",np.int8)])
a=np.array([(10,),(20,),(30,)])
print(a)

Example:

student=np.dtype([("name","S20"),("age","i1"),("marks","f4")])
a=np.array([("abc", 21, 50),("xyz", 18, 75)], dtype=student)

每个数据类型都有一个代表字母:
+ ‘b’: boolean
+ ‘i’: (signed)integer
+ ‘u’: unsigned integer
+ ‘f’: floating-point
+ ‘c’: complex-floating point
+ ‘m’: timedelta
+ ‘M’: datetime
+ ‘O’: (Python)objects
+ ‘S’,’a’: (byte-)string
+ ‘U’: Unicode
+ ‘V’: raw data(void)


ndarray.shape

返回一个包含数组维度的tuple,也可用来调整数组大小。

Example:

a=np.array([[1,2,3],[4,5,6]])
print(a.shape)

Example:

a=np.array([[1,2,3],[4,5,6]])
a.shape=(3,2)
print(a)

Example:

a=np.array([[1,2,3],[4,5,6]])
b=a.reshape(3,2)
print(b)

ndarray.ndim

返回数组维度个数

Example:

a=np.arange(20)
b=a.reshape(4,5)

numpy.itemsize

返回数组中每个元素的字节大小

Example:

x=np.array([1,2,3,4,5], dtype=np.int8)
print(x.itemsize)

numpy.flags

ndarray对象有如下的属性,通过函数能返回当前的属性值。
+ C_CONTIGUOUS(C):
+ F_CONTIGUOUS(F):
+ OWNDATA(O):
+ WRITEABLE(W):
+ ALIGNED:
+ UPDATEIFCOPY(U):

Example:

x=np.array([1,2,3,4,5])
print(x.flags)

新的ndarray对象可用下面任意的方法创建或者使用低层的ndarray构造。

numpy.empty

创建一个带shape和dtype的数组,不进行初始化:

numpy.empty(shape, dtype=float, order="C")

Example:

x=np.empty([3,2], dtype=int)
print(x)

为什么我这里的输出是元素值为0的数组?

numpy.zeros

返回特定shape的零矩阵。

numpy.zeros(shape, dtype=float, order="C")

Example:

# Dafault dtype is float.
x=np.zeros(5)
# Different with the last one.
x=np.zeros((5,), dtype=np.int)
# points in 2-D dimention
x=np.zeros((2,2), dtype=[("x","i4"),("y","i4")])

numpy.ones

返回特定shape的全1矩阵。

numpy.ones(shape, dtype=None, order="C")

Example:

x=np.ones(5)
x=np.ones([2,2], dtype=int)

从已知数据中构造数组。

numpy.asarray

类似于numpy.array,但是参数不一样,多适用于将Python序列转化为ndarray。

numpy.asarray(a, dtype=None, order=None)

Example:

x=[1,2,3]
a=np.asarray(x)
# a=np.asarray(x, dtypr=float)
print(a)

Example:

x=(1,2,3)
a=np.asarray(x)
print(a)

numpy.frombuffer

该函数接受buffer输入转化为ndarray对象。

numpy.frombuffer(buffer, dtype=float, count=-1, offset=0)

Example:

s="Hello World"
a=np.frombuffer(s, dtype="s1")
# 没有跑成功,提示str对象没有__buffer__方法

numpy.fromiter

该函数从可迭代对象中建立ndarray对象,返回一维数组。

numpy.fromiter(iterable, dtype, count=-1)

Example:

list=range(5)
it=iter(list)
x=np.fromiter(it, dtype=float)
print(x)

numpy.arange

该函数返回一组有相同间隔的ndarray数值对象。

numpy.arange(start, stop, step, dtype)

Example:

x=np.arange(5, dtype=float)
x=np.arange(10, 20, 2)

numpy.linspace

该函数作用类似numpy.arange,不同在于这里不给出step,给的间隔略复杂,看参数和例子吧。

numpy.linspace(start, stop, num, endpoint, retstep, dtype)

Example:

x=np.linspace(10, 20, 5)
x=np.linspace(10, 20, 5, endpoint=False)
x=np.linspace(1, 2, 3, retstep=True)

numpy.logspace

返回有log级别间隔的ndarray对象。实质上我的理解是,返回一组指数间隔的对象,底数一般取10,也可在参数中用关键字base来指定。

numpy.logscale(start, stop, num, endpoint, base, dtype)

注意:start和stop这两个指数都会取到,所以实质上的间隔是(stop-start)/(num-1)。

Example:

a=np.logspace(1.0, 2.0, num=10)
a=np.logspace(1, 10, num=10, base=2)

ndarray对象可以由索引和切片来查看和改变,类似Python内置容器对象。

之前讲过,内部元素索引以0开始,有三种方式访问索引,field access, basic slicingadvanced indexing

基本切片是Python中切为n维度数据等基本内容的拓展,Python中的切片是给出start, stopstep,这里的切片可以给一个数组为参数。

Example:

a=np.arange(10)
x=slice(2,7,2)
print(a[s])
# b=a[2:7:2]
# print(b)
# print(a[5])
# print(a[2:])

Example:

a=np.array([[1,2,3],[3,4,5],[4,5,6]])
print("Now we will slice the array from the index a[1:] 
",a[1:])
print("The items in the second column are: 
",a[...,1])
print("The items in the second row are: 
",a[1,...])

若是需要非tuple序列、整数或者布尔类型ndarray,或者其中一个元素是list的tuple对象,都有可能选择ndarray对象来实现。高级索引通常返回的是数据的副本,与此相对的是,切片操作仅能看到对象。有两种高级索引,IntegerBoolean

Interger Indexing

这里切片用的每个整数表示数组中的索引值(或者说,数组下标)。

Example:

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

说明:整数切片表示取的点是(0,0),(1,1)和(2,0)。

Example:

x=np.array([[0,1,2],[3,4,5],[6,7,8],[9,10,11]])
rows=np.array([[0,0],[3,3]])
cols=np.array([[0,2],[0,2]])
y=x[rows, cols]
print(y)
# >>> [[0 2]
#       [9 11]]

高级和基本的索引能用slice(:)和ellipsis(…)联合起来组成索引数组,下面的例子用slice来生成行索引,用高级索引来生成列索引,效果与同用slice相同,区别是高级索引会生成副本,可能在内存的使用上有差异。

Example:

x=np.array([[0,1,2],[3,4,5],[6,7,8],[9,10,11]])
# slicing
z=x[1:4,1:3]
print(z)
# >>>   [[4 5]
#       [7 8]
#       [10 11]]
# advanced index
y=x[1:4,[1,2]]
print(y)
# >>>[[4 5]
#       [7 8]
#       [10 11]]

Boolean Array Indexing

这种索引多用于需要逻辑判断的场景,由于逻辑判断的结果是布尔类型,所以称之为布尔数组索引。

Example:

x=np.array([[0,1,2],[3,4,5],[6,7,8],[9,10,11]])
print(x[x>5])
# >>>   [6 7 8 9 10 11]

Example:

a=np.array([np.nan, 1, 2, np,nan, 3, 4, 5])
print(a[~np.isnan(a)])
# >>> [1. 2. 3. 4. 5.]

Example:

a=np.array([1, 2+6j, 5, 3.5+5j])
print(a[np.iscomplex(a)])
# >>> [2.0+6.j 3.5+5.j]

用于Numpy处理不同维度的数组算术问题,算术符号一般作用于相应元素,如果两个数组同shape,那么算术符可以畅通无阻的作用。

Example:

a=np.array([1,2,3,4])
b=np.array([10,20,30,40])
c=a*b
print(c)
# >>>[10 40 90 160]

如果两个数组的shape不一样,相应元素的算术操作就无法实现,但是在Numpy中却有这个可能,因为broadcasting有这个能力。shape小的数组会broadcast成大数组的size,然后就可以进行元素运算。满足一下条件可以运用broadcasting:
+ ndim较小的数组预先处理为‘1’shape;# ?
+ 输出shape中的每个维度都是输入维度中的最大值;# ?
+ 如果输入在某个维度上的大小与输出匹配或者值为1,那么可以用在计算中;
+ 如果输入维度是1,该维度上的第一个数会被用在其每个元素上。

若是满足上面条件,且下列任意一项为真,那么数组可称为broadcast的数组:
+ 有相同shape的数组;
+ 有相同维度的数组,每个唯独的长度为1或一个相同的值;
+ 维度较小的数组能预先将其处理为1. #?

Example:

a=np.array([[0.0,0.0,0.0],[10,10,10],[20,20,20],[30.0,30.0,30.0]])
b=np.array([1.0, 2.0, 3.0])
print(a+b)
# >>> [[1. 2. 3.]
#       [11. 12. 13.]
#       [21. 22. 23.]
#       [31. 32. 33.]]

NumPy中包含一个迭代器对象 numpy.nditer,作用于多维度问题,甚至可以迭代数组。数组中的每个元素都是用Python标准迭代器接口访问。

Example:

a=np.arange(0, 60, 5)
a=a.reshape(3,4)
print("Original array is: 
",a)
print("Changed array is: ")
for x in np.nditer(a):
    print(x)
# >>>Original array is:
#       [[0 5 10 15]
#       [20 25 30 35]
#       [40 45 50 55]]
#   Changed array is: 0 5 10 15 20 25 30 35 40 45 50 55

迭代匹配的是数组所在内存顺序,不考虑其他特定顺序,可参见下面的遍历矩阵转置的例子。

Example:
a=np.arange(0, 60, 5)
a=a.reshape(3,4)
b=a.T
for x in np.nditer(b):
print(x)
# >>> Changed array is: 0 5 10 15 20 25 30 35 40 45 50 55

Modifying Array Values

nditer对象有个名为op_flags的参数,默认参数是只读,但也能设置为读写或者仅写入模式,所以可以用这个迭代器来修改数组的元素值。

Example:

a=np.arange(0, 60, 5)
a=a.reshape(3,4)
for x in np.nditer(a, op_flags=["readwriter"]):
    x[...]=2*x

External Loop

nditer类构造函数有一个flags参数,可取值如下:
+ c_index
+ f_index
+ multi-index
+ external_loop

Example:

a=np.arange(0, 60, 5)
a=a.reshape(3,4)
for x in np.nditer(a, flags=["external_loop"], order="F"):
    print(x)
# >>>   [0 20 40][5 25 45][10 30 50][15 35 55]

Broadcasting Iteration

如果两个数组是broadcastable,同样有nditer对象可用来迭代。比如说,假如数组a的维度是3X4,数组b的维度是1X4,那么迭代器同样可按下面方式使用(将b拓展到a的大小):

Example:

a=np.arange(0, 60, 5)
a=a.reshape(3,4)
b=np.array([1,2,3,4], dtype=int)
for x,y in np.nditer([a,b]):
    print("%d:%d"%(x,y))

操作NumPy包中ndarray的元素有几种方式,可分为以下几类:

Changing Shape

  • reshape
  • flat
  • flatten
  • ravel

Transpose Operations

  • transpose
  • ndarray.T
  • rollavis
  • swapaxes

Changing Dimensions

  • broadcast
  • broadcast_to
  • expand_dims
  • squeeze
  • concatenate
  • stack
  • hstack
  • vstack

Splitting Arrays

  • split
  • hsplit
  • vsplit

Adding/Removing Elements

  • resize
  • append
  • insert
  • delete
  • unique

numpy.reshape

numpy.reshape(arr, newshape, order)

参数order可选’C’或者’F’,‘C’是C语言风格,’F’是Fortran风格,‘A’表示Fortran风格的连续存储方式,否则就是‘C’风格。

Example:

a=np.arange(8)
b=a.reshape(4,2)

numpy.ndarray.flat

返回数组上的一维迭代器,类似Python上建立的迭代器。

Example:

a=np.array(8).reshape(2,4)
print(a.flat[5])

numpy.ndarray.flatten

ndarray.flatten(order)

order参数说明:默认’C’是行占优,’F’是列占优。

Example:

a=np.array(8).reshape(2,4)
print(a.flatten())
print(a.flatten(order="F"))

numpy.ravel

返回扁平的一维数组,必要的时候才生成副本。输出与输入有相同的元素类型。

numpy.ravel(a, order)

Example:

a=np.array(8).reshape(2,4)
print(a.ravel())
print(a.ravel(oeder="F"))

numpy.transpose

返回矩阵转置。

numpy.transpose(arr, axes)

Example:

a=no.arange(12).reshape(3,4)
print(np.transpose(a))

numpy.ndarray.T

该方程属于ndarray类,作用类似于numpy.transpose

Example:

a=np.arange(12).reshape(3,4)
print(a.T)

numpy.swapaxes

该函数交换数组两个坐标轴。

numpy.swapaxes(arr, axis1, axis2)

Example:

a=np.arange(8).reshape(2,2,2)
print(np.swapaxes(a,2,0))

numpy.rollaxis

从某个位置开始,旋转坐标轴到某一个特定位置。

numpy.rollaxis(arr, axis, start)

start默认取值为0。

Example:

a=np.arange(8).reshape(2,2,2)
print(np.rollaxis(a,2))
print(np.rollaxis(a,2,1))

numpy.broadcast

该函数模仿广播机制,接受两个数组为输入。

Example:

x=np.array([[1],[2],[3]])
y=np.array([4,5,6])
b=np.broadcast(x,y)
r,c=b.iters
print(r.next(), c.next())
print(r.next(), c.next())
print(b.shape)
c=np.empty(b.shape)
print(c.shape)
c.flat=[u+v for (u,v) in b]
print(c)
print(x+y)

numpy.broadcast_to

该函数将数组广播为一个新的shape,返回原数组一个只读视图,是个非连续的,还可能会返回不满足NumPy广播规则的ValueError。

numpy.broadcast_to(array, shape, subok)

Example:

a=np.arange(4).reshape(1,4)
print(a)
print(np.broadcast_to(a,(4,4)))

NumPy包里提供如下位操作:
+ bitwise_and
+ bitwise_or
+ invert
+ left_shift
+ right_shift


当dtype=numpy.string或者numpy.unicode,他们是基于Python标准库建立的。
+ add()
+ numtiply()
+ center()
+ capitalize()
+ title()
+ lower()
+ upper()
+ split()
+ splitlines()
+ strip()
+ join()
+ replace()
+ decode()
+ encode()



数学运算包括,add(),subtract(),multiply(),divide()。


NumPy有一些诸如minimum,maximum等有用的统计函数。










声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。