Python数据挖掘(一)之Numpy

一、基本操作

  • ndarray.方法()
  • numpy.函数名()

二、ndarray与Python原生list运算效率对比

import numpy as np
import random
import time

# 生成一个大数组
python_list = []

for i in range(10000000):
    python_list.append(random.random())

ndarray_list = np.array(python_list)
# 原生pythonlist求和
t1 = time.time()
a = sum(python_list)
t2 = time.time()

# ndarray求和
t3 = time.time()
b = np.sum(ndarray_list)
t4 = time.time()

d1 = t2-t1
d2 = t4-t3
print(d1,d2)
运行结果:
0.2780158519744873 0.039002418518066406

三、ndarray的属性

属性名字属性解释
ndarray.shape数组维度的元组
ndarray.ndim数组维度
ndarray.size数组中的元素数量
ndarray.itemsize一个数组元素的长度(字节)
ndarray.dtype数组元素的类型
import numpy as np
score = np.array([[80,89,86,67,79],
[78,97,89,67,81],
[90,94,78,67,74],
[91,91,90,67,69],
[76,87,75,67,86],
[70,79,84,67,84],
[94,92,93,67,64],
[86,85,83,67,80]])

score.shape #(8,5)
score.ndim  # 2
score.size  # 40
score.dtype # dtype('int32')
score.itemsize # 4

四、ndarray的形状

import numpy as np
a = np.array([[1,2,3],[4,5,6]])
b = np.array([1,2,3,4])
c = np.array([[[1,2,3],[4,5,6]],[[1,2,3],[4,5,6]]])
a.shape # (2,3)     二维数组
b.shape # (4,)      一维数组
c.shape # (2,2,3)   三维数组

五、ndarray的类型

名称描述简写
np.bool用一个字节储存的布尔类型(True或False)‘b’
np.int8一个字节大小,-128至127‘i’
np.int16整数,-32768至32767‘i2’
np.int32整数,-2^31至2**32 -1‘i4’
np.int64整数,-2^63至2**63 -1‘i8’
np.uint8无符号字符,0至255‘u’
np.uint16无符号字符,0至65535‘u2’
np.uint32无符号字符,0至2**32-1‘u4’
np.uint64无符号字符,0至2**64-1‘u8’
np.float16半精度浮点数:16位,正负号1位,指数5位,精度10位‘f2’
np.float32半精度浮点数:32位,正负号1位,指数8位,精度23位‘f4’
np.float64半精度浮点数:64位,正负号1位,指数11位,精度52位‘f8’
np.complex64复数,分别用两个32位浮点数表示实部和虚部‘c8’
np.complex128复数,分别用两个64位浮点数表示实部和虚部‘c16’
np.object_python对象‘O’
np.string_字符串‘S’
np.unicode_unicode类型‘U’
a = np.array([[1,2,3],[4,5,6]],dtype=np.float32)
b = np.array([[1,2,3],[4,5,6]],dtype='float32')

六、生成数组的方法

1、生成0和1的数组(加粗为常用)

  • empty(shape[,dtype,order])
    empty_like(a[,dtype,order,subok])
    eye(N[,M,k,dtype])
  • identity(n[,dtype])
  • ones(shape[,dtype,order])
    ones_like(a[,dtype,order,subok])
  • zeros(shape[,dtype,order])
    zeros_like(a[,dtype,order,subok])
  • full(shape,fill_value[,dtype,order])
    full_like((a,fill_value[,dtype,order,subok])
a = np.zeros([3,4],dtype='float32')
结果显示:
array([[0., 0., 0., 0.],
       [0., 0., 0., 0.],
       [0., 0., 0., 0.]],dtype='float32')
       
b = np.ones((3,4),dtype=np.int32)
结果显示:
array([[1, 1, 1, 1],
       [1, 1, 1, 1],
       [1, 1, 1, 1]])

2、从现有数组生成

  • array(object[,dtype,copy,order,subok,ndmin])
  • asarray(a[,dtype,order])
  • asanyarray(a[,dtype,order])
  • ascontiguousarray(a[,dtype])
  • asmatrix(data[,dtype])
  • copy(a[,order])
score
结果显示:
array([[80, 89, 86, 67, 79],
       [78, 97, 89, 67, 81],
       [90, 94, 78, 67, 74],
       [91, 91, 90, 67, 69],
       [76, 87, 75, 67, 86],
       [70, 79, 84, 67, 84],
       [94, 92, 93, 67, 64],
       [86, 85, 83, 67, 80]])
       
a = np.array(score)
array([[80, 89, 86, 67, 79],
       [78, 97, 89, 67, 81],
       [90, 94, 78, 67, 74],
       [91, 91, 90, 67, 69],
       [76, 87, 75, 67, 86],
       [70, 79, 84, 67, 84],
       [94, 92, 93, 67, 64],
       [86, 85, 83, 67, 80]])
       
b = np.asarray(score)
array([[80, 89, 86, 67, 79],
       [78, 97, 89, 67, 81],
       [90, 94, 78, 67, 74],
       [91, 91, 90, 67, 69],
       [76, 87, 75, 67, 86],
       [70, 79, 84, 67, 84],
       [94, 92, 93, 67, 64],
       [86, 85, 83, 67, 80]])
       
c = np.copy(score)
array([[80, 89, 86, 67, 79],
       [78, 97, 89, 67, 81],
       [90, 94, 78, 67, 74],
       [91, 91, 90, 67, 69],
       [76, 87, 75, 67, 86],
       [70, 79, 84, 67, 84],
       [94, 92, 93, 67, 64],
       [86, 85, 83, 67, 80]])
       
score[3,1]=100
score
array([[ 80,  89,  86,  67,  79],
       [ 78,  97,  89,  67,  81],
       [ 90,  94,  78,  67,  74],
       [ 91, 100,  90,  67,  69],
       [ 76,  87,  75,  67,  86],
       [ 70,  79,  84,  67,  84],
       [ 94,  92,  93,  67,  64],
       [ 86,  85,  83,  67,  80]])
       
a
array([[80, 89, 86, 67, 79],
       [78, 97, 89, 67, 81],
       [90, 94, 78, 67, 74],
       [91, 91, 90, 67, 69],
       [76, 87, 75, 67, 86],
       [70, 79, 84, 67, 84],
       [94, 92, 93, 67, 64],
       [86, 85, 83, 67, 80]]

b
array([[ 80,  89,  86,  67,  79],
       [ 78,  97,  89,  67,  81],
       [ 90,  94,  78,  67,  74],
       [ 91, 100,  90,  67,  69],
       [ 76,  87,  75,  67,  86],
       [ 70,  79,  84,  67,  84],
       [ 94,  92,  93,  67,  64],
       [ 86,  85,  83,  67,  80]])

c
array([[80, 89, 86, 67, 79],
       [78, 97, 89, 67, 81],
       [90, 94, 78, 67, 74],
       [91, 91, 90, 67, 69],
       [76, 87, 75, 67, 86],
       [70, 79, 84, 67, 84],
       [94, 92, 93, 67, 64],
       [86, 85, 83, 67, 80]]

3、生成固定范围的数组

  • np.linspace(start,stop,num,endpoint,retstep,stype)
    • start:起始值
    • stop:终止值
    • num:生成的等间隔样例数,默认50
    • endpoint:是否包含stop值,默认为True
    • retstep:如果为True,返回样例以及连续数字之间的步长
    • dtype:输出ndarray的数据类型
  • np.arange(start,stop,step,dtype)
  • np.logspace(start,stop,num,endpoint,base,dtype)
np.linspace(0,100,11)

结果显示:
rray([  0.,  10.,  20.,  30.,  40.,  50.,  60.,  70.,  80.,  90., 100.])

np.arange(0,100,11)

结果显示:
array([ 0, 11, 22, 33, 44, 55, 66, 77, 88, 99])

4、生成随机数组

  • np.random模块
  • 均匀分布
  • np.random.uniform(low=0.0,high=1.0,size=None)
    • 左闭右开
    • low:采样下界,float类型,默认值为0
    • high:采样上界,float类型,默认值为1
    • size:输出样本数目,为int或元组(tuple)类型
    • 返回值:ndarray类型,其形状和参数size中描述一致
data = np.random.uniform(low=-1,high=1,size=1000000)
结果显示:
array([ 0.29973032, -0.99592522, -0.12878166, ...,  0.4671398 ,
        0.73620789, -0.61035304])
  • 画图看分布情况
import numpy as np
import matplotlib.pyplot as plt

data1 = np.random.uniform(low=-1,high=1,size=1000000)

plt.figure(figsize=(20,8),dpi=80)
plt.hist(data1,1000)
plt.show()

在这里插入图片描述

  • 正态分布
  • np.random.normal(loc=0.0,scale-1.0,size=None)
    • loc:概率分布的均值,float类型,默认为0
    • scale:标准差,float类型,默认为1
    • size:输出的shape,为int或元组(tuple)类型
import numpy as np
import matplotlib.pyplot as plt

data2 = np.random.normal(loc=1.75,scale=0.1,size=1000000)

plt.figure(figsize=(20,8),dpi=80)
plt.hist(data2,1000)
plt.show()

在这里插入图片描述
七、切片索引与形状修改

# 随机生成8只股票2周10天的交易日涨幅数据
stock_change = np.random.normal(loc=0,scale=1,size=(8,10))
stock
结果显示:
array([[ 0.28866518,  0.49007035, -1.0295688 ,  1.01683992,  1.01519649,
        -0.29999328, -0.76637183,  0.3234394 ,  0.74618983, -0.74521678],
       [ 1.10970872,  0.43847635,  0.10793209, -0.33875262,  1.24097958,
         1.15689848, -1.35141042,  0.46076134, -0.72427958,  3.00917696],
       [ 0.85608048,  2.67827804,  0.23806889, -0.52764946, -1.46812416,
         0.81891667,  0.39902141,  0.38002871, -0.01470654, -0.71823495],
       [-0.19468438, -0.63961257,  0.00528773, -0.71138971,  0.60533562,
         0.8800105 , -1.04492792,  0.4097555 , -1.25950243, -0.28323795],
       [ 0.07019306,  0.51475206,  1.40270703,  0.37329934,  0.88638178,
        -0.16880721,  0.75616533,  0.07438347,  0.14462213,  0.15672049],
       [ 1.04271929,  2.0699429 ,  0.64498365, -1.32930153,  0.36577287,
        -1.44287423,  1.22969138,  1.35187119, -0.77311966, -0.07487412],
       [ 2.8215247 , -0.88633269, -1.06810978,  0.5667001 , -0.29615515,
        -0.79718657, -0.40368762, -0.29615865, -0.30359228, -1.01969044],
       [-0.04145257,  0.4040836 ,  1.11395625,  1.61802583,  0.72781171,
         0.70617192,  0.85293105,  2.90987162, -0.41458456,  0.52759134]])
         
#获取第一支股票的前三个交易日的涨跌幅数据
stock_change[0,:3]
结果显示:
array([ 0.28866518,  0.49007035, -1.0295688 ])

#需求:转置——股票行、日期列反过来,变为日期行、股票列
stock_change.reshape((10,8)) #返回新的ndarray,原始数据没有改
stock_change.resize((10,8))  #没有返回值,对原始的ndarray进行了修改
stock_change.T
结果显示:
array([[ 0.28866518,  0.49007035, -1.0295688 ,  1.01683992,  1.01519649,
        -0.29999328, -0.76637183,  0.3234394 ],
       [ 0.74618983, -0.74521678,  1.10970872,  0.43847635,  0.10793209,
        -0.33875262,  1.24097958,  1.15689848],
       [-1.35141042,  0.46076134, -0.72427958,  3.00917696,  0.85608048,
         2.67827804,  0.23806889, -0.52764946],
       [-1.46812416,  0.81891667,  0.39902141,  0.38002871, -0.01470654,
        -0.71823495, -0.19468438, -0.63961257],
       [ 0.00528773, -0.71138971,  0.60533562,  0.8800105 , -1.04492792,
         0.4097555 , -1.25950243, -0.28323795],
       [ 0.07019306,  0.51475206,  1.40270703,  0.37329934,  0.88638178,
        -0.16880721,  0.75616533,  0.07438347],
       [ 0.14462213,  0.15672049,  1.04271929,  2.0699429 ,  0.64498365,
        -1.32930153,  0.36577287, -1.44287423],
       [ 1.22969138,  1.35187119, -0.77311966, -0.07487412,  2.8215247 ,
        -0.88633269, -1.06810978,  0.5667001 ],
       [-0.29615515, -0.79718657, -0.40368762, -0.29615865, -0.30359228,
        -1.01969044, -0.04145257,  0.4040836 ],
       [ 1.11395625,  1.61802583,  0.72781171,  0.70617192,  0.85293105,
         2.90987162, -0.41458456,  0.52759134]])

八、类型修改与数组去重

# 类型修改
stock_change.astype('int32')
结果显示:
array([[ 0,  0, -1,  1,  1,  0,  0,  0,  0,  0],
       [ 1,  0,  0,  0,  1,  1, -1,  0,  0,  3],
       [ 0,  2,  0,  0, -1,  0,  0,  0,  0,  0],
       [ 0,  0,  0,  0,  0,  0, -1,  0, -1,  0],
       [ 0,  0,  1,  0,  0,  0,  0,  0,  0,  0],
       [ 1,  2,  0, -1,  0, -1,  1,  1,  0,  0],
       [ 2,  0, -1,  0,  0,  0,  0,  0,  0, -1],
       [ 0,  0,  1,  1,  0,  0,  0,  2,  0,  0]])

# ndarray序列化到本地,转换成bytes类型
stock_change.tostring()
# 数组的去重
temp = np.array([[1,2,3,4],[3,4,5,6]])
np.unique(temp)
结果显示:
array([1, 2, 3, 4, 5, 6])

# 降维
a = temp.flatten()
结果显示:
array([1, 2, 3, 4, 3, 4, 5, 6])

set(a)
结果显示:
{1, 2, 3, 4, 5, 6}

九、ndarray运算

1、逻辑运算

stock_change = np.random.normal(0,1,(8,10))
stock_change1 = stock_change[:5,:5]
#逻辑判断,如果涨幅大于0.5就标记为True,否则为False
stock_change1 > 0.5
结果显示:
array([[ True, False, False, False, False],
       [False, False, False, False, False],
       [False, False,  True, False, False],
       [ True, False,  True, False,  True],
       [False,  True,  True,  True, False]])
       
# 布尔索引
stock_change1[stock_change1 > 0.5] = 1
stock_change1
结果显示:
array([[ 1.        , -0.46765002,  0.13243126, -0.84527941,  0.15635903],
       [-1.40424928, -2.25548311,  0.02521395,  0.33559729, -0.00654103],
       [ 0.38896488,  0.43402995,  1.        , -0.15885148,  0.38292029],
       [ 1.        , -1.06229789,  1.        , -1.55423623,  1.        ],
       [-0.18001979,  1.        ,  1.        ,  1.        , -1.26822918]])

2、通用判断函数

  • np.all(布尔值)
    • 只要有一个False就返回False,只有全是True才返回True
  • np.any(布尔值)
    • 只要有一个True就返回True,只有全是False才返回False
stock_change = np.random.normal(0,1,(8,10))
np.all(stock_change<20)
True
np.any(stock_change<1)
True

3、np.where(三元运算符)

  • np.where(布尔值,True的位置的值,False的位置的值)
  • 符合逻辑需要结合np.logical_and和np.logical_or使用
# 判断前四个股票前四天的涨幅,大于0的置为1,否则为0
temp = stock_change[:4,:4]
np.where(temp>0,1,0)
结果显示:
array([[0, 1, 1, 1],
       [1, 0, 0, 0],
       [1, 1, 1, 0],
       [0, 1, 0, 0]])
#大于0.5并且小于1/大于0.5或者小于-0.5,为1,否则为0 
np.where(np.logical_and(temp>0.5,temp<1),1,0)
np.where(np.logical_or(temp>0.5,temp<-0.5),1,0)

4、统计运算

  • 统计指标函数:min,max,mean,median,var,std
  • np.函数名(a[,axis,out,keepdims])
  • ndarray.方法名()
#求最大值
stock_change.max()
np.max(stock_change)

# 按列求最大值
stock_change.max(axis=0)
np.max(stock_change,axis=0)

# 按行求最大值
stock_change.max(axis=1)
np.max(stock_change,axis=1)
结果显示:
array([1.40061582, 0.33725661, 1.89656721, 1.41261175, 0.61338125,
       0.97553906, 0.75111251, 2.76915945])

#返回每列最小值所在位置
np.argmin(stock_change,axis=0)

#返回每行最大值所在位置
np.argmax(stock_change,axis=1)
结果显示:
array([5, 0, 0, 1, 6, 8, 5, 8], dtype=int32)

十、数组间的运算

# 数组与数的运算
arr = np.array([[1,2,3,2,1,4],[5,6,1,2,3,1]])
arr + 10
结果显示:
array([[11, 12, 13, 12, 11, 14],
       [15, 16, 11, 12, 13, 11]])

# 数组与数组的运算(遵循广播机制)
arr1 = np.array([[1,2,3,2,1,4],[5,6,1,2,3,1]])
arr2 = np.array([[1,2,3,2,1,4],[5,6,1,2,3,1]])
arr1 + arr2
结果显示:
array([[ 2,  4,  6,  4,  2,  8],
       [10, 12,  2,  4,  6,  2]])

arr3 = np.array([[1,2,3,2,1,4],[5,6,1,2,3,1]])
arr4 = np.array([[1],[3]])
arr3 + arr4
结果显示:
array([[2, 3, 4, 3, 2, 5],
       [8, 9, 4, 5, 6, 4]])

#矩阵运算(线性代数)
# ndarray存储矩阵
a = np.array([[80,86],[82,80],[85,78],[90,90],[86,82],[82,90],[78,80],[92,94]])
# matrix存储矩阵
np.mat(a)

# 矩阵乘法计算
a = np.array([[80,86],[82,80],[85,78],[90,90],[86,82],[82,90],[78,80],[92,94]])
b = np.array([[0.3],[0.7]])
a @ b
np.mat(a) * np.mat(b)
np.matmul(a,b)
np.dot(a,b)
结果显示:
matrix([[84.2],
        [80.6],
        [80.1],
        [90. ],
        [83.2],
        [87.6],
        [79.4],
        [93.4]])

十一、合并与分割

1、合并

  • np.hstack(tup) 水平拼接
  • np.vstack(tup) 竖直拼接
  • np.concatenate((a1,a2,…),axis=0)
a = np.array((1,2,3))
b = np.array((2,3,4))
np.hstack((a,b))
结果显示:
array([1, 2, 3, 2, 3, 4])

np.vstack((a,b))
结果显示:
array([[1, 2, 3],
       [2, 3, 4]])

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

# 默认axis=0
np.concatenate((a,b),axis=0)
结果显示:
array([[1, 2],
       [3, 4],
       [5, 6]])

np.concatenate((a,b.T),axis=1)
结果显示:
array([[1, 2, 5],
       [3, 4, 6]])

2、分割

  • np.split(ary,indices_or_sections,axis=0)
x= np.arange(9)
np.split(x,3)
结果显示:
[array([0, 1, 2]), array([3, 4, 5]), array([6, 7, 8])]

x=np.arange(8)
np.split(x,[3,5,6,10])
结果显示:
[array([0, 1, 2]),
 array([3, 4]),
 array([5]),
 array([6, 7]),
 array([], dtype=int32)]

十二、IO操作和数据处理
1、Numpy读取

  • np.genfromtxt(fname[,dtype,comments,…])
import numpy as np
data = np.genfromtxt('test.csv',delimiter=',')
# delimiter=',' 逗号分隔符分隔
结果显示:
array([[  nan,   nan,   nan,   nan],
       [  1. , 123. ,   1.4,  23. ],
       [  2. , 110. ,   nan,  18. ],
       [  3. ,   nan,   2.1,  19. ]])

2、缺失值处理

用numpy处理很麻烦,后续介绍pandas

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值