,慢慢来吧,重新从小白开始,欢迎大佬拍砖!这里学习主要参考:http://scipy.github.io/old-wiki/pages/Numpy_Example_List
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 22 15:18:07 2018
@author: Shawn
"""
# =============================================================================
# # numpy 模块函数学习
# =============================================================================
import numpy as np
# 产生4*4数组并转换为矩阵
test = np.mat(np.random.rand(4,4))
# 求逆
invtest = test.I
myeye = test*invtest
myeye
# eye创建单位阵
myeye - np.eye(4)
# =============================================================================
# -1- arange([start,] stop[, step,], dtype=None)
# 序列生成函数
# =============================================================================
#help(np.arange)
#arange函数,默认从0开始,只给一个参数则默认为stop,
#给两个以上参数,默认第一个是起始数字,第二个是截至数字,
#第三个是间隔,还可以定义数据类型,类似R的seq()
np.arange(12)
np.arange(3.)
np.arange(3,7)
np.arange(3,10,2)
# =============================================================================
# -2- reshape(a, newshape, order='C')
# 重设维数
# =============================================================================
#help(np.reshape)
a = np.zeros((10,2))
b = a.T # 转置
c = b.view()
c.shape = (20)
a = np.arange(6)
a.reshape((3,2)) # 重新给定维数
np.reshape(a, (2,3))
np.reshape(a, (2,3), order='C')
np.reshape(a, (2,3), order='F')
np.reshape(a, (2,3), order='A')
np.ravel(a, order = 'F')
x = np.arange(3)
x[:,np.newaxis] # 增加1维
x[:,np.newaxis].shape
x[:,np.newaxis,np.newaxis] # 增加2维
x[:,np.newaxis,np.newaxis].shape
x1 = x[:,np.newaxis,np.newaxis] * x
x1.shape
x[np.newaxis,:] # 等价于x[np.newaxis] 和 x[None]
x[np.newaxis,:].shape
x[:,np.newaxis].shape
#由以上代码可以看出,当把newaxis放在前面的时候,
#以前的shape是3,现在变成了1×3,也就是前面的维数发生了变化,
#而把newaxis放后面的时候,后面的维数发生了变化,
#输出的新数组的shape就是3×1,也就是后面增加了一个维数,
#所以,newaxis放在第几个位置,就会在shape里面看到相应的位置增加了一个维数
x = np.random.randint(1,8,size=(2,3,4))
x.shape
x[0]
x[1]
x[1,2]
x[1,2,3]
y = x[:,np.newaxis,:,:]
y.shape
#Out[68]: (2, 1, 3, 4)
z = x[:,:,np.newaxis,:]
z.shape
#Out[69]: (2, 3, 1, 4)
#经常会遇到这样的问题,需要从数组中取出一部分的数据
#,也就是取出“一片”或者“一条”,比如需要从二维数组里面抽取一列
#取出来之后维度却变成了一维,假如我们需要将其还原为二维,就需要上面的方法了
# =============================================================================
# -3- array(object, dtype=None, copy=True, order='K', subok=False, ndmin=0)
# 数组对象
# =============================================================================
help(np.array)
a = np.array([1,2,3]) # 整数型
a = np.array([1,2,3.]) # 浮点型
b = np.array([[1,2],[3,4.]])
b.shape
#Out[81]: (2, 2)
c = np.array([[1,2],[3,4.]], ndmin = 3) # ndim指定生成的最小维数
c.shape
#Out[82]: (1, 2, 2)
np.array(np.arange(4), dtype=complex) # dtype指定数据类型
#Out[84]: array([ 0.+0.j, 1.+0.j, 2.+0.j, 3.+0.j])
x = np.array([(1,2),(3,4)], dtype=[('a','<i4'),('b','<i4')])
x['a']
#Out[91]: array([1, 3])
a = np.array(np.arange(20))
b = a.reshape(4,5)
b[0,0] # 数组索引也是从0开始
b[-1] # 最后一行,与b[-1,]和b[-1,:]等价
b[:,-1] # 最后一列
b[0:2,0:2] # 索引取子集
i = np.array[0,1,2,3] # 第一维索引
j = np.array[0,1,2,3] # 第二维索引
b[i,j] # 提取索引数字
b[b<10] # 布尔值索引
b[[True,False,True,True],:] # 布尔值行索引,类似可进行列索引
#定义数组元素描述
#方法1
mydesc = {'names': ('gender','age','weight'), 'formats': ('S1','f4','f4')}
type(mydesc)
data = np.array([('m',28.0,65.0),('f',35.0,55.0)], dtype=mydesc)
print(data)
#[(b'm', 28., 65.) (b'f', 35., 55.)]
data['age']
#Out[49]: array([ 28., 35.], dtype=float32)
data.dtype.names
#Out[51]: ('gender', 'age', 'weight')
#方法2
mydesc2 = [('age',np.int16),('house',np.int8),('weight',np.float32)]
data2 = np.array([(33,3,67.5),(66,2,50)], dtype=mydesc2)
type(data2)
#Out[59]: numpy.ndarray
data2['age']
#Out[60]: array([33, 66], dtype=int16)
#矩阵数组之间转换
m = np.matrix('1 2;5 8;0 3')
a = np.asarray(m)
np.asanyarray(m)
m = np.asmatrix(np.arange(8).reshape(2,4))
# =============================================================================
# -4- abs 绝对值函数
# =============================================================================
# help(np.abs)
abs(-1) # 内置函数
np.abs(-1)
abs(np.array([-2,-3]))
abs(1+1j)
# =============================================================================
# -5- accumulate(array, axis=0, dtype=None, out=None, keepdims=None)
# 累计运算
# =============================================================================
#help(np.add.accumulate)
a = np.array(np.arange(1,5.))
np.add.accumulate(a) # 向后累加
#Out[134]: array([ 1., 3., 6., 10.])
np.multiply.accumulate(a) # 向后累乘
#Out[135]: array([ 1., 2., 6., 24.])
b = np.reshape(np.arange(1,9.), [2,4])
np.add.accumulate(b, axis=0) # axis 指定以第几个维度累计运算,缺失则默认第0个
#Out[137]:
#array([[ 1., 2., 3., 4.],
# [ 6., 8., 10., 12.]])
np.add.accumulate(b, axis=1)
#Out[138]:
#array([[ 1., 3., 6., 10.],
# [ 5., 11., 18., 26.]])
np.add([1,2], [2,3])
#Out[141]: array([3, 5])
#isinstance([1,2],list)
#type([1,2])
# =============================================================================
# -6- np.all(a, axis=None, out=None, keepdims=<class 'numpy._globals._NoValue'>)
# 判断一个数组是否全部为真
# =============================================================================
# help(np.all)
a = np.arange(5)
a.all() # 等价于 np.all(a)
#Out[150]: False
all(a)
all(a>=0) # 等价于 (a>=0).all()
any(a) # 判断元素至少一个为真则为真
#Out[156]: True
any([0,0,0])
#Out[157]: False
# =============================================================================
# -7- angle(z, deg=0)
# 返回复数的弧度(radians)和角度(degrees),默认是弧度
# =============================================================================
#help(np.angle)
import math
np.angle([1.0, 1.0j, 1+1.0j]) # 返回弧度
#Out[183]: array([ 0. , 1.57079633, 0.78539816])
np.angle([1.0, 1.0j, 1+1.0j], deg = True) # deg 指定返回角度还是弧度
#Out[184]: array([ 0., 90., 45.])
# 换算公式:角度 = 180*弧度/pi
180*np.angle([1.0, 1.0j, 1+1.0j], deg = False)/math.pi
#Out[185]: array([ 0., 90., 45.])
# =============================================================================
# -8- append(arr, values, axis=None)
# 在数组末尾添加元素
# insert(arr, obj, values, axis=None)
# 在数组内插入元素
# =============================================================================
#help(np.append)
help(np.insert)
a = np.arange(4)
np.append(a, 100)
#Out[188]: array([ 0, 1, 2, 3, 100])
b = np.arange(9).reshape([3,3])
np.append(b, [1,1,1]) # 直接以序列末添加
#Out[191]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 1, 1, 1])
np.append(b, [[1,1,1]], axis=0) # 第0维末添加
#Out[193]:
#array([[0, 1, 2],
# [3, 4, 5],
# [6, 7, 8],
# [1, 1, 1]])
np.append(b, [[1],[1],[1]], axis=1) # 第1维末添加
#Out[195]:
#array([[0, 1, 2, 1],
# [3, 4, 5, 1],
# [6, 7, 8, 1]])
np.insert(a, [1,3], 10) # 在第1,3个元素前插入10
#Out[197]: array([ 0, 10, 1, 2, 10, 3])
np.insert(a, [1,3], [10,100]) # 在第1,3个元素前插入10,100
#Out[198]: array([ 0, 10, 1, 2, 100, 3])
np.insert(b, [1,2], 100)
#Out[201]: array([ 0, 100, 1, 100, 2, 3, 4, 5, 6, 7, 8])
np.insert(b, [1,2], 100, axis=0) # 在数组第0维的1,2个元素前插入100
#Out[202]:
#array([[ 0, 1, 2],
# [100, 100, 100],
# [ 3, 4, 5],
# [100, 100, 100],
# [ 6, 7, 8]])
np.insert(b, [1,2], [[100],[200]], axis=0) # 在数组第0维的1,2个元素前插入100,200
#Out[205]:
#array([[ 0, 1, 2],
# [100, 100, 100],
# [ 3, 4, 5],
# [200, 200, 200],
# [ 6, 7, 8]])
np.insert(b, [1,2], 100, axis=1) # 在数组第1维的1,2个元素前插入100
#Out[203]:
#array([[ 0, 100, 1, 100, 2],
# [ 3, 100, 4, 100, 5],
# [ 6, 100, 7, 100, 8]])
# =============================================================================
# -9- apply_along_axis(func1d, axis, arr, *args, **kwargs)
# 将数组按指定维度应用函数,类似R的apply
# apply_over_axes(func, a, axes) 类似功能
# =============================================================================
#help(np.apply_along_axis)
#定义函数:返回第0和最后一个元素均值
def myfunc(a):
return (a[0]+a[-1])/2
b = np.arange(9).reshape([3,3])
np.apply_along_axis(myfunc, 0, b)
#Out[211]: array([ 3., 4., 5.])
np.apply_along_axis(myfunc, 1, b)
#Out[212]: array([ 1., 4., 7.])
# =============================================================================
# -10- argmax(a, axis=None, out=None)
# 返回轴上最大值的索引
# argmin(a, axis=None, out=None)
# 返回轴上最小值的索引,与argmax语法一致
# amax(a, axis=None, out=None, keepdims=<class 'numpy._globals._NoValue'>)
# 返回轴上的最大值,相应的有min()
# maximum(x1, x2[, out])
# 比较两个数组返回最大元素的新数组
# =============================================================================
#help(np.argmax)
a = np.arange(1,10,2)
a
#Out[15]: array([1, 3, 5, 7, 9])
np.argmax(a)
#Out[16]: 4
a[np.argmax(a)]
#Out[17]: 9
b = np.arange(6).reshape(2,3)
np.argmax(b)
b.ravel()[np.argmax(b)] # ravel将数组降为1维
np.argmax(b, axis=0)
np.argmax(b, axis=1)
c = np.insert(b,[0,2],[[5],[2]], axis=1)
c
#Out[73]:
#array([[5, 0, 1, 5, 2],
# [2, 3, 4, 2, 5]])
np.argmax(c, axis=1) # 只返回首次出现符合条件的索引
#Out[74]: array([0, 4], dtype=int64)
#help(np.max)
np.max(b, axis=1)
#Out[76]: array([2, 5])
np.min(b, axis=1)
#Out[77]: array([0, 3])
np.max(b)
#Out[78]: 5
d = np.arange(2)
np.min(b,out= d, axis=1)
e = np.arange(5, dtype=np.float)
e[2] = np.NAN
np.amin(e)
#Out[101]: nan
np.nanmin(e)
#Out[102]: 0.0
# help(np.maximum)
np.maximum([2, 3, 4], [1, 5, 2])
#Out[104]: array([2, 5, 4])
np.maximum(np.eye(2), [0.5, 2]) # 行之间比较,传播效应:存在矩阵则传播为矩阵比较
#Out[105]:
#array([[ 1. , 2. ],
# [ 0.5, 2. ]])
np.eye(2)
#Out[106]:
#array([[ 1., 0.],
# [ 0., 1.]])
np.maximum(np.Inf, 1) # 无穷大比较
#Out[108]: inf
np.maximum([np.nan, 0, np.nan], [0, np.nan, np.nan])


雷达卡




京公网安备 11010802022788号







