-- coding: utf-8 --

“””
演示NumPy数组的一些基本功能。
“””
import numpy as np
#########创建数组
先创建序列对象,使用array()转换为数组

a = np.array([1, 2, 3, 4])
b = np.array((5, 6, 7, 8))
c = np.array([[1, 2, 3, 4],[4, 5, 6, 7], [7, 8, 9, 10]])
print b
print c

数组的形状通过shape属性获得,描述数组各个轴长度

print a.shape
print c.shape

c.shape = 4,3 #并非转置,只是改变每个轴的大小,数组元素在内存中的位置不变
print c

c.shape = 2, -1 #自动计算-1轴的长度,当前为6
print c

d = a.reshape((2,2))
print d

a[1] = 100 #将a数组的第一个元素修改,d中相应位置也发生变化,a和d共享数据存储空间
print d

print c.dtype #数组的元素类型

e = np.array([
[1, 2, 3, 4],
[4, 5, 6, 7],
[7, 8, 9, 10]], dtype=np.float)

print e

f = np.array([
[1, 2, 3, 4],
[4, 5, 6, 7],
[7, 8, 9, 10]], dtype=np.complex)

print f

print np.typeDict[“d”]
print np.typeDict[“double”]
print np.typeDict[“float64”]
print set(np.typeDict.values())

创建数组的函数

print np.arange(0, 1, 0.1) #开始为0,终值为1不出现在数组中,步长为0.1
print np.linspace(0, 1, 12) #开始,终值,元素个数,步长为1/9
np.linspace(0,1,10,endpoint = False) #步长为1/10,endpoint的值会改变数组的等差步长
print np.logspace(0, 2, 20) #起始值为10^0,终值为10^2,5个元素的等比数组
np.logspace(0,1,12,base = 2,endpoint = False) #创建一个比例为2^(1/12)的等比数组

np.empty((2,3),np.int) #只分配内存,不进行初始化
np.zeros(4,np.float) #元素初始化为0的数组
np.ones() #元素初始化为1

从字节序列或文件创建数组

s = “abcdefgh” #字节序列,每个字符占一个字节
np.fromstring(s,dtype = np.int8) #得到字符串中每个字符的ASCII编码
np.fromstring(s,dtype = np.int16) #以低位字节在前方式存储,98*256+97等四个元素的数组
np.fromstring(s,dtype =np.float) #64bit的双精度浮点数数组

使用fromfunction函数创建数组

def func(i):
return i%4 + 1

print np.fromfunction(func, (10,))

def func2(i,j):
return (i+1)*(j+1)

print np.fromfunction(func2, (9,9)) #九九乘法表的二维数组

-- coding: utf-8 --

“””
演示一维数组的下标存取。
“””
import numpy as np

a = np.arange(10)
print “a[5]”, a[5] #用整数作为下标,可以获取数组中的某个元素
print “a[3:5]”, a[3:5] #用切片作为下标,包括3不包括5
print “a[:5]”, a[:5] #切片中省略开始下标,表示从0开始
print “a[:-1]”, a[:-1] #负数表示从数组最后往前数
a[2:4] = 100,101 #修改元素的值
print “a”, a
print “a[1:-1:2]”, a[1:-1:2] #切片中第三个元素表示步长,2表示隔一个取一个元素
print “a[::-1]”, a[::-1] #省略起始下标,步长为-1,将整个数组头尾颠倒
print “a[5:1:-2]”, a[5:1:-2] #步长为负数,开始下标大于结束下标

b = a[3:7] #切片获得的新数组与原数组同享一块数据存储空间,改变一处相应变化
print b
b[2] = -10
print b
print a

x = np.arange(10,1,-1)
print x
print “x[[3, 3, 1, 8]]”, x[[3, 3, 1, 8]]
b = x[np.array([3,3,-3,8])]
b[2] = 100
print b
print x
x[[3,5,1]] = -1, -2, -3
print x

x = np.arange(5,0,-1)
print x
print x[np.array([True, False, True, False, False])]
print x[[True, False, True, False, False]]
print x[np.array([True, False, True, True])]
x[np.array([True, False, True, True])] = -1, -2, -3
print x

x = np.random.rand(10)
print x
print x>0.5
print x[x>0.5]

-- coding: utf-8 --

“””
演示二维数组的下标存取。采用元组作为数组的下标
“””
import numpy as np

a = np.arange(0, 60, 10).reshape(-1, 1) + np.arange(0, 6) #创建加法表,6*6的数组
print (“a[0,3:5]=”, a[0,3:5])
print (“a[4:,4:]=”, a[4:,4:])
print (“a[:,2]=”, a[:,2])
print (“a[2::2,::2]=”, a[2::2,::2])

b = a[0,3:5] #b与a共享数据空间,随之改变
b[0] = -b[0]
print (“a[0,3:5]=”, a[0,3:5])

idx = slice(None, None, 2), slice(2,None) #slice(开始,结束值,间隔步长)生成切片,省略时使用None
print (“idx = “, idx)
print (“a[idx]=”, a[idx]) # 和a[::2,2:]相同
print (“a[idx][idx]=”, a[idx][idx])# 和a[::2,2:][::2,2:]相同

print (a[(0,1,2,3,4),(1,2,3,4,5)])
print (a[3:, [0,2,5]])
mask = np.array([1,0,1,0,0,1], dtype=np.bool)
print (a[mask, 2])
mask = np.array([1,0,1,0,0,1])
print (a[mask, 2])

-- coding: utf-8 --

“””
ufunc是universal function的缩写,能对数组中每个元素进行操作的函数。
测试ufnuc函数的速度。
“””
import time
import math
import numpy as np

x = np.linspace(0,2*np.pi,10) #产生0到2pi的等差数组,并计算每个元素正弦值

y = np.sin(x)

print(y)

t = np.sin(x,out=x) #out参数指定计算结果的保存位置

print(x)

id(t) == id(x)

Numpy计算和python库的计算速度比较

x = [i * 0.001 for i in xrange(1000000)]
start = time.clock()
for i, t in enumerate(x):
x[i] = math.sin(t)
print (“math.sin:”, time.clock() - start)

x = [i * 0.001 for i in xrange(1000000)]
x = np.array(x)
start = time.clock()
np.sin(x,x)
print (“numpy.sin:”, time.clock() - start)

x = [i * 0.001 for i in xrange(1000000)]
start = time.clock()
for i, t in enumerate(x):
x[i] = np.sin(t)
print (“numpy.sin loop:”, time.clock() - start)

a = np.arange(6.0).reshape(2,3)
a.item(1,2) #和a[1,2]类似
type(a.item(1,2)) #item()返回的是python的标准float类型
type(a[1,2]) #下标方式返回的是Numpy的float64类型

Numpy提供多个ufunc函数

a = np.arange(0,4)
b = np.arange(1,5)
print(np.add(a,b)) #add()返回一个数组,数组的每个元素是两个参数数组中对应元素之和
print(np.add(a,b,a)) #不指定out参数,将创建新数组保存结果;指定out参数,则直接保存到指定数组。等同于a+=b
“””
数组的运算符及对应的ufunc函数列表
y = x1 + x2 add(x1, x2 [, y])
y = x1 - x2 subtract(x1, x2 [, y])
y = x1 * x2 multiply (x1, x2 [, y])
y = x1 / x2 divide (x1, x2 [, y]), 如果两个数组的元素为整数,那么用整数除法
y = x1 / x2 true divide (x1, x2 [, y]), 总是返回精确的商
y = x1 // x2 floor divide (x1, x2 [, y]), 总是对返回值取整
y = -x negative(x [,y])
y = x1 ** x2 power(x1, x2 [, y])
y = x1 % x2 remainder(x1, x2 [, y]), 或mod(x1, x2, [, y])
“”“

注意:表达式运算会产生中间结果而降低程序的运行效率

x = a*b+c #等同于 t = a*b, x=t+c,del t 会产生临时数组t,应修改如下:
x = a*b
x += c

比较和bool运算

result = np.array([1,2,3])

-- coding: utf-8 --

import numpy as np

“””
使用NumPy快速读取CSV文件。
“”“

采用字符串数组读取文件

tmp = np.loadtxt(“test.csv”, dtype=np.str, delimiter=”,”)

将部分数组的值进行转换

data = tmp[1:,1:].astype(np.float)
print (data)

定义结构数组元素的类型

persontype = np.dtype({
‘names’:[‘name’, ‘age’, ‘weight’, ‘height’],
‘formats’:[‘S32’,’i’, ‘f’, ‘f’]})

f = file(“test.csv”)
f.readline() # 跳过第一行
data = np.loadtxt(f, dtype=persontype, delimiter=”,”)
f.close()
print (data)
#
tofile()将数组中的数据以二进制格式写进文件

tofile()输出的数据不保存数组形状和元素类型等信息

fromfile()函数读回数据时需要用户指定元素类型,并对数组的形状进行适当的修改

a = np.arange(0,12)
a.shape = 3,4
a.tofile(“a.bin”)
b = np.fromfile(“a.bin”,dtype = np.float) #按照float类型读入数据,读入数据是错误的
a.type #查看a的dtype
b = np.fromfile(“a.bin”,dtype = np.int32) #按照int32类型读入数据,数据是一维的
b.shape = 3,4 #修改其shape,得到正确结果
#
np.save(“a.npy”,a) #使用save和load可以自动处理元素类型和形状,专用的二进制格式保存数据
c = np.load(“a.npy”)

a = np.array([1,2,3],[4,6,6])
b = np.arange(0,1.0,0.1)
c = np.sin(b)
np.savez(“result.npz”,a,b,sin_array = c)
#savez()可以将多个数组保存到一个文件,第一个参数为文件名,其中每个文件都是save()保存的npy文件
r = np.load(“result.npz”) # npz文件包括:arr_0.npy, arr_1.npy, sin_array.npy
r[“arr_0”] #数组a
r[“arr_1”] #数组b
r[“sin_array”] #数组c
#
a = np.arange(0,12,0.5).reshape(4,-1)
np.savetxt(“a.txt”,a) #默认按照‘%。18e’格式保存数值,以空格间隔
np.loadtxt(“a.txt”)

np.savetxt(“a.txt”,a,fmt = “%d”,delimiter = “,”) # 保存为整数,以逗号间隔
np.loadtxt(“a.txt”,delimiter = “,”) #读入是指定逗号分隔

友情链接
ioDraw流程图
API参考文档
OK工具箱
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:637538335
关注微信