您的位置:首页 > 编程语言 > Python开发

NumPy学习笔记(1)

2014-11-06 16:09 225 查看
1. 程序开头导入库

import numpy as np

2. 创建数组(ndarray)

a = [1,2,3,4]

aa = np.array(a)--------->生成一维数组

bb = np.array([a,a])----->生成二维数组

aa.shape

bb.shape------------------>获得尺寸(2, 4)

bb.shape = (1,8) ---------> Reshape为1X8数组,8可以用-1表示,这样自动计算尺寸

c = bb.reshape(2,4)------>用reshape函数获得新数组,注意这里c与bb共享存储空间。若想隔离,需要用copy()函数

3. 数组的类型

bb.dtype------------------------>获得bb的数值类型,可能为int32, int64, float64, complex128等

生成不同数值类型的数组:

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

完整的类型列表:

>>> set(np.typeDict.values())
set([<type 'numpy.bool_'>, <type 'numpy.int8'>, <type 'numpy.void'>, <type 'numpy.int32'>, <type 'numpy.uint32'>, <type 'numpy.float128'>, <type 'numpy.string_'>, <type 'numpy.uint8'>, <type 'numpy.float32'>, <type 'numpy.complex256'>, <type 'numpy.int64'>,
<type 'numpy.uint64'>, <type 'numpy.complex64'>, <type 'numpy.unicode_'>, <type 'numpy.uint64'>, <type 'numpy.int16'>, <type 'numpy.uint16'>, <type 'numpy.float64'>, <type 'numpy.object_'>, <type 'numpy.complex128'>, <type 'numpy.int64'>])

4. 几个专门创建数组的函数

np.arrange(start, end, step)---------------->生成等差数列,不包括end值

np.linspace(start, end, num)--------------------------->生成等差数列,默认包括end值

np.linspace(start, end, num, endpoint=False)-------->不包括end值

np.logspace(start, end, num, base, endpoint)------------------------->生成等比数列

np.zeros(size, dtype), np.zeros_like(other)

np.ones(size, dtype),np.ones_like(other)

np.random.rand(size, dtype)------------------------------------>生成随机数组

np.empty(size, dtype)--------------------------------------------->仅分配空间,不初始化,最快!

np.fromstring(str, dtype)-------------------------------------------->从字符串创建数组

np.frombuffer()

np.fromfile()

np.fromfunction(funcname, size)

5. 数组的切片和下标访问

一维数组的索引如下:

0,1,2,。。。-3,-2,-1,即负数会从后往前数

a[start:end:step]----------------------->取数组的一个切片,与原数组共享内存。不包括end值。

省略start,表示start = 0;

省略end,表示end = -1;

省略step,表示step = 1;

单独生成切片可以用slice函数

slice(start, end, step) = start:end:step

slice(None, end, step) = :end:step

slice(None, None, None) = :

另外也可以用s_对象生成slice

>>> np.s_[::2,2:]
(slice(None, None, 2), slice(2, None, None))

二维数组取一次下标,得到一维数组(想想C中的数组)

多次下标可以用元组方式,如x[2][2]等价于x[2,2],或者直观一点x[(2,2)]

整数索引列表查表

idx = [1, 4, 5, 7]

y = x[idx]------------------->取出x中[1,4,5,7]位置处的值,放入y,不和原数组共享内存

整数数组也是一样的

布尔数组(np.array([True, False, True,...])):只取数组中相应位置为True的元素;

布尔列表[True, False, True, ...]:将按照整数方式取, True = 1, False = 0.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: