楼主: 阿扁V5
1597 1

[数据挖掘工具] python学习——numpy [推广有奖]

  • 1关注
  • 43粉丝

版主

山野小子

已卖:965份资源

副教授

94%

还不是VIP/贵宾

-

威望
0
论坛币
-29467312 个
通用积分
3823.6007
学术水平
108 点
热心指数
119 点
信用等级
91 点
经验
49334 点
帖子
1168
精华
1
在线时间
651 小时
注册时间
2013-3-22
最后登录
2024-3-17

楼主
阿扁V5 学生认证  发表于 2018-8-2 22:50:18 |AI写论文

+2 论坛币
k人 参与回答

经管之家送您一份

应届毕业生专属福利!

求职就业群
赵安豆老师微信:zhaoandou666

经管之家联合CDA

送您一个全额奖学金名额~ !

感谢您参与论坛问题回答

经管之家送您两个论坛币!

+2 论坛币
平时工作也比较忙,坚持学习已经很难,如果再坚持分享就真的是难上加难了,前段时间学习了python的基础语法及数据结构,由于本人主要从事数据挖掘(之前工作主要使用R和sas),偏工程应用,对开发内容暂时还没深入的需求,先数据挖掘必备的一些把基础打牢,最近在学习numpy库了,先在分享部分常用的函数及用法案例,每天利用零碎时间都学不了几个,慢慢来吧,重新从小白开始,欢迎大佬拍砖!
这里学习主要参考: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])



二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝


憧憬机器学习的世界!

沙发
阿扁V5 学生认证  发表于 2018-8-2 22:53:30
# =============================================================================
# -11- argsort(a, axis=-1, kind='quicksort', order=None)
# 排序函数
# =============================================================================
help(np.argsort)

a = np.array([2,5,1,6,3,9])
ind = np.argsort(a)
ind
#array([2, 0, 4, 1, 3, 5], dtype=int64)
a[ind] # 等价于np.sort(a)
#array([1, 2, 3, 5, 6, 9])
ind = np.argsort(a, kind='heap')
ind = np.argsort(a, order=0)

b = np.reshape(a, [2,3])
b
#Out[32]:
#array([[2, 5, 1],
#       [6, 3, 9]])
ind0 = np.argsort(b, axis=0)
ind0
#Out[33]:
#array([[0, 1, 0],
#       [1, 0, 1]], dtype=int64)
ind1 = np.argsort(b, axis=1) # 用axis=-1表示对最后一个轴排序
ind1
#Out[34]:
#array([[2, 0, 1],
#       [1, 0, 2]], dtype=int64)

c = np.ones(20)
c.argsort()
c.argsort(kind='merge') # 稳定性较quick更佳


# =============================================================================
# -12- array_split(ary, indices_or_sections, axis=0)
# 划分数组为多个子数组
# =============================================================================
help(np.array_split)

x = np.arange(10.)
np.array_split(x,3) # 分割为3部分,前一个部分元素个数>=后一部分
#Out[64]: [array([ 0.,  1.,  2.,  3.]), array([ 4.,  5.,  6.]), array([ 7.,  8.,  9.])]
out_x = np.array_split(x,3)
out_x[0]

y = np.reshape(x,[2,5])
np.array_split(y, 2, axis=0) # 逐行分割为两部分
#Out[68]: [array([[ 0.,  1.,  2.,  3.,  4.]]), array([[ 5.,  6.,  7.,  8.,  9.]])]
np.array_split(y, 4, axis=0) # 逐行分割为4部分,不足则为空
#Out[70]:
#[array([[ 0.,  1.,  2.,  3.,  4.]]),
# array([[ 5.,  6.,  7.,  8.,  9.]]),
# array([], shape=(0, 5), dtype=float64),
# array([], shape=(0, 5), dtype=float64)]
np.array_split(y, 2, axis=1)
#Out[71]:
#[array([[ 0.,  1.,  2.],
#        [ 5.,  6.,  7.]]), array([[ 3.,  4.],
#        [ 8.,  9.]])]
np.array_split(y, [1,3], axis=1) # 在第1,3列前划分
#Out[73]:
#[array([[ 0.],
#        [ 5.]]), array([[ 1.,  2.],
#        [ 6.,  7.]]), array([[ 3.,  4.],
#        [ 8.,  9.]])]  


# =============================================================================
# -13- atleast_1d(*arys)
# atleast_2d(*arys)
# atleast_3d(*arys)
# 将对象转换维至少1/2/3维的数组
# =============================================================================

help(np.atleast_3d)
a=1.0 # 标量
a
np.shape(a)
np.atleast_1d(a) # 标量转换为至少1维的数组
np.shape(np.atleast_1d(a))
np.atleast_2d(a) # 标量转换为至少2维的数组
np.shape(np.atleast_2d(a))
np.atleast_3d(a) # 标量转换为至少3维的数组
np.shape(np.atleast_3d(a))

b = np.arange(4) # 一维数组
np.shape(b)
np.atleast_1d(b)
np.shape(np.atleast_1d(b))
np.atleast_2d(b) # 一维数组转换为至少2维的数组
np.shape(np.atleast_2d(b))
np.atleast_3d(b) # 一维数组转换为至少3维的数组
np.shape(np.atleast_3d(b))

c = np.arange(9).reshape(3,3) # 二维数组
np.shape(c)
np.atleast_1d(c)
np.shape(np.atleast_1d(c))
np.atleast_2d(c) # 二维数组转换为至少2维的数组
np.shape(np.atleast_2d(c))
np.atleast_3d(c) # 二维数组转换为至少3维的数组
np.shape(np.atleast_3d(c))


# =============================================================================
# -14- average(a, axis=None, weights=None, returned=False)
# 返回对象在指定维度的加权平均
# =============================================================================
help(np.average)

np.average(np.arange(4))
a = np.arange(1,4)
a
#Out[158]: array([1, 2, 3])
weight = np.arange(30,0,-10)
weight
#Out[159]: array([30, 20, 10])
np.average(a, weights=weight) # 加权平均sum(Wi*Xi)/sum(Wi)
#Out[160]: 1.6666666666666667
(1*30 + 2*20 +3*10)/(30+20+10)
#Out[161]: 1.6666666666666667
np.average(a, weights=weight, returned=True)  # 返回权重和
#Out[162]: (1.6666666666666667, 60.0)


# =============================================================================
# -15- bincount(x, weights=None, minlength=None)
# 对数组终非负整数统计出现的次数
# =============================================================================
help(np.bincount)

a = np.array([1,1,1,1,2,2,4,4,5,6,6,6]) # 无需排序
np.bincount(a)
#Out[165]: array([0, 4, 2, 0, 2, 1, 3], dtype=int64)
# 0:0次,1:4次,2:2次,。。。
a = np.array([5,4,4,2,2])
w = np.array([0.1, 0.2, 0.1, 0.3, 0.5])
np.bincount(a)
#Out[166]: array([0, 0, 2, 0, 2, 1], dtype=int64)
np.bincount(a, weights=w) # w的shape与a一致
#Out[167]: array([ 0. ,  0. ,  0.8,  0. ,  0.3,  0.1])
#0,1的权重为0,2的权重为0.3+0.5,3未出现,4的权重为0.2+0.1,5的权重为0.1

# =============================================================================
# -16- np.random.beta(a,b,size=None) 贝塔分布
# np.random.binomial()
# np.random.normal()
# np.random.chisquare()
# =============================================================================

#beta分布
np.random.beta(a=1,b=10,size=(2,3))
#二项分布,n为试验次数,p为发生概率
np.random.binomial(n=100,p=0.5,size=(2,2))
import pylab as pb
pb.hist(np.random.binomial(100,0.5,size=1000), 20)
# 正态分布
np.random.normal(loc=0,scale=1,size=(3,3))
pb.hist(np.random.normal(0,1,1000), 50)
# 卡方分布
np.random.chisquare(3,size=(10))
pb.hist(np.random.chisquare(3,size=(10000)), 50)
# 指数分布
np.random.exponential(scale=1.0, size=5)
pb.hist(np.random.exponential(scale=1.0, size=10000), 50)


# =============================================================================
# -17-  bmat(obj, ldict=None, gdict=None)
# 从字符串,嵌套序列或数组构建矩阵对象
# =============================================================================

a = np.mat('1 2; 3 4')
b = np.mat('5 6; 7 8')
np.bmat('a b; b a')
np.bmat([[a,b], [b,a]]) # 与上式等价
#Out[2]:
#matrix([[1, 2, 5, 6],
#        [3, 4, 7, 8],
#        [5, 6, 1, 2],
#        [7, 8, 3, 4]])


# =============================================================================
# -18- np.broadcast()
# 返回一个广播结果,有迭代器的作用
# =============================================================================
a = np.array([[1,2],[3,4]])
b = np.array([5,6])
c = np.broadcast(a, b)
c.nd # 返回广播结果的维度
#Out[41]: 2
c.shape # 广播结果的形状
#Out[42]: (2, 2)
c.size # 广播结果的大小
#Out[43]: 4
c.index # 迭代次数
c.reset() # 结果重置(迭代次数),再次运行下面循环需重置
for value in c:
    print('迭代次数:{num}\n迭代值:{val}!'.format(num=c.index, val=value))

#迭代次数:1
#迭代值:(1, 5)!
#迭代次数:2
#迭代值:(2, 6)!
#迭代次数:3
#迭代值:(3, 5)!
#迭代次数:4
#迭代值:(4, 6)!

您需要登录后才可以回帖 登录 | 我要注册

本版微信群
加好友,备注cda
拉您进交流群
GMT+8, 2026-1-16 16:53