numpy1

数据分析:是把隐藏在一些看似杂乱无章的数据背后的信息提炼出来,总结出所研究对象的内在规律

数据分析三剑客:Numpy,Pandas,Matplotlib

NumPy(Numerical Python) 是 Python 语言的一个扩展程序库,支持大量的维度数组与矩阵运算,此外也针对数组运算提供大量的数学函数库。

一、创建ndarray

1. 使用np.array()创建

  • 一维数据创建
import numpy as np
arr1 = np.array([1,2,3,4,5])
arr1
array([1, 2, 3, 4, 5])
  • 二维数组创建
arr1 = np.array([[1,'two',3],[4,5,6]])
arr1
array([['1', 'two', '3'],
       ['4', '5', '6']], dtype='<U11')

注意:

  • numpy默认ndarray的所有元素的类型是相同的

  • 如果传进来的列表中包含不同的类型,则统一为同一类型,优先级:str>float>int

  • 使用matplotlib.pyplot获取一个numpy数组,数据来源于一张图片

import matplotlib.pyplot as plt
img_arr = plt.imread('./cat.jpg')
plt.imshow(img_arr)
<matplotlib.image.AxesImage at 0x88fd898>

png

img_arr = img_arr - 50
plt.imshow(img_arr)
<matplotlib.image.AxesImage at 0x948d9b0>

png

  • 操作该numpy数据,该操作会同步到图片中
img_arr.shape
(456, 730, 3)

2. 使用np的routines函数创建

  1. np.full(shape, fill_value, dtype=None, order='C')
np.full(shape=(5,6),fill_value=666)
array([[666, 666, 666, 666, 666, 666],
       [666, 666, 666, 666, 666, 666],
       [666, 666, 666, 666, 666, 666],
       [666, 666, 666, 666, 666, 666],
       [666, 666, 666, 666, 666, 666]])
  1. np.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None) 等差数列
np.linspace(0,100,num=10)
array([  0.        ,  11.11111111,  22.22222222,  33.33333333,
        44.44444444,  55.55555556,  66.66666667,  77.77777778,
        88.88888889, 100.        ])
  1. np.arange([start, ]stop, [step, ]dtype=None)
np.arange(0,100,2)
array([ 0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32,
       34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66,
       68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98])
  1. np.random.randint(low, high=None, size=None, dtype='l')
np.random.randint(0,100,size=(6,7))
array([[11, 80, 27, 97, 17, 48, 50],
       [76, 21, 38, 93, 69, 41, 57],
       [13, 96, 73, 77, 56, 13, 88],
       [69, 24, 33,  4, 11, 44, 88],
       [ 1, 60, 10, 18,  0, 21, 84],
       [55, 20, 11, 36, 68, 30, 30]])
#固定随机性(随机因子)
np.random.seed(10)
np.random.randint(0,100,size=(6,7))
array([[ 9, 15, 64, 28, 89, 93, 29],
       [ 8, 73,  0, 40, 36, 16, 11],
       [54, 88, 62, 33, 72, 78, 49],
       [51, 54, 77, 69, 13, 25, 13],
       [92, 86, 30, 30, 89, 12, 65],
       [31, 57, 36, 27, 18, 93, 77]])
  1. np.random.random(size=None)

生成0到1的随机数,左闭右开 np.random.seed(3)

np.random.random(size=(4,5))
array([[0.76545582, 0.01178803, 0.61194334, 0.33188226, 0.55964837],
       [0.33549965, 0.41118255, 0.0768555 , 0.85304299, 0.43998746],
       [0.12195415, 0.73173462, 0.13878247, 0.76688005, 0.83198977],
       [0.30977806, 0.59758229, 0.87239246, 0.98302087, 0.46740328]])

二、ndarray的属性

4个必记参数:
ndim:维度
shape:形状(各维度的长度)
size:总长度

dtype:元素类型

img_arr.ndim
3
img_arr.size
998640
img_arr.dtype
dtype('uint8')
type(img_arr)
numpy.ndarray

三、ndarray的基本操作

1. 索引

一维与列表完全一致
多维时同理

arr1[0][1]
'two'

根据索引修改数据

2. 切片

一维与列表完全一致
多维时同理

np.random.seed(1)
arr = np.random.randint(0,100,size=(5,6))
arr
array([[37, 12, 72,  9, 75,  5],
       [79, 64, 16,  1, 76, 71],
       [ 6, 25, 50, 20, 18, 84],
       [11, 28, 29, 14, 50, 68],
       [87, 87, 94, 96, 86, 13]])
#获取二维数组前两行
arr[0:2]
array([[37, 12, 72,  9, 75,  5],
       [79, 64, 16,  1, 76, 71]])
#获取二维数组前两列
arr[:,0:2]
array([[37, 12],
       [79, 64],
       [ 6, 25],
       [11, 28],
       [87, 87]])
#获取二维数组前两行和前两列数据
arr[0:2,0:2]
array([[37, 12],
       [79, 64]])

将数据反转,例如[1,2,3]---->[3,2,1]

::进行切片

arr
array([[37, 12, 72,  9, 75,  5],
       [79, 64, 16,  1, 76, 71],
       [ 6, 25, 50, 20, 18, 84],
       [11, 28, 29, 14, 50, 68],
       [87, 87, 94, 96, 86, 13]])
#将数组的行倒序
arr[::-1]
array([[87, 87, 94, 96, 86, 13],
       [11, 28, 29, 14, 50, 68],
       [ 6, 25, 50, 20, 18, 84],
       [79, 64, 16,  1, 76, 71],
       [37, 12, 72,  9, 75,  5]])
#列倒序
arr[:,::-1]
array([[ 5, 75,  9, 72, 12, 37],
       [71, 76,  1, 16, 64, 79],
       [84, 18, 20, 50, 25,  6],
       [68, 50, 14, 29, 28, 11],
       [13, 86, 96, 94, 87, 87]])
#全部倒序
arr[::-1,::-1]
array([[13, 86, 96, 94, 87, 87],
       [68, 50, 14, 29, 28, 11],
       [84, 18, 20, 50, 25,  6],
       [71, 76,  1, 16, 64, 79],
       [ 5, 75,  9, 72, 12, 37]])
#将图片进行全倒置操作
plt.imshow(img_arr)
<matplotlib.image.AxesImage at 0xb9238d0>

png

plt.imshow(img_arr[:,::-1,:])
<matplotlib.image.AxesImage at 0xbb42f60>

png

plt.imshow(img_arr[::-1,:,:])
<matplotlib.image.AxesImage at 0xbbbea58>

png

plt.imshow(img_arr[::-1,::-1,::-1])
<matplotlib.image.AxesImage at 0xb4042b0>

png

3. 变形

使用arr.reshape()函数,注意参数是一个tuple!

  • 基本使用

    1.将一维数组变形成多维数组

arr.reshape((2,3))
array([['1', 'two', '3'],
       ['4', '5', '6']], dtype='<U11')
arr.reshape((2,-1))
array([['1', 'two', '3'],
       ['4', '5', '6']], dtype='<U11')

2.将多维数组变形成一维数组

arr = arr1.reshape((6))

4. 级联

  • np.concatenate()

1.一维,二维,多维数组的级联,实际操作中级联多为二维数组

a1 = np.random.randint(0,100,size=(4,5))
a2 = np.random.randint(0,100,size=(4,5))
a3 = np.random.randint(0,100,size=(4,4))
display(a1,a2,a3)
array([[25, 22,  9, 67, 23],
       [27, 37, 57, 83, 38],
       [ 8, 32, 34, 10, 23],
       [15, 87, 25, 71, 92]])



array([[74, 62, 46, 32, 88],
       [23, 55, 65, 77,  3],
       [ 0, 77,  6, 52, 85],
       [70,  2, 76, 91, 21]])



array([[75,  7, 77, 72],
       [75, 76, 43, 20],
       [30, 36,  7, 45],
       [68, 57, 82, 96]])
np.concatenate((a1,a2),axis=1)
array([[ 9,  7, 63, 61, 22, 49, 57,  3, 68, 24],
       [57,  1,  0, 60, 81, 43, 76, 26, 52, 80],
       [ 8, 88, 13, 47, 72, 41, 82, 15, 64, 68],
       [30, 71,  3, 70, 21, 25, 98, 87,  7, 26]])
np.concatenate((a1,a3),axis=1)
array([[25, 22,  9, 67, 23, 75,  7, 77, 72],
       [27, 37, 57, 83, 38, 75, 76, 43, 20],
       [ 8, 32, 34, 10, 23, 30, 36,  7, 45],
       [15, 87, 25, 71, 92, 68, 57, 82, 96]])

2.合并两张照片

img_arr = plt.imread('./cat.jpg')

img_3 = np.concatenate((img_arr,img_arr,img_arr),axis=1)
img_9 = np.concatenate((img_3,img_3,img_3),axis=0)
plt.imshow(img_9)
<matplotlib.image.AxesImage at 0xbb075c0>

png

3.np.hstack与np.vstack

级联需要注意的点:

  • 级联的参数是列表:一定要加中括号或小括号
  • 维度必须相同
  • 形状相符:在维度保持一致的前提下,如果进行横向(axis=1)级联,必须保证进行级联的数组行数保持一致。如果进行纵向(axis=0)级联,必须保证进行级联的数组列数保持一致。
  • 可通过axis参数改变级联的方向

5. 切分

与级联类似,三个函数完成切分工作:

  • np.split(arr,行/列号,轴):参数2是一个列表类型
  • np.vsplit
  • np.hsplit
a1
array([[25, 22,  9, 67, 23],
       [27, 37, 57, 83, 38],
       [ 8, 32, 34, 10, 23],
       [15, 87, 25, 71, 92]])
np.split(a1,[2],axis=1)
[array([[25, 22],
        [27, 37],
        [ 8, 32],
        [15, 87]]), array([[ 9, 67, 23],
        [57, 83, 38],
        [34, 10, 23],
        [25, 71, 92]])]

切分照片

plt.imshow(img_arr)
<matplotlib.image.AxesImage at 0xb7a8780>

png

plt.imshow(img_arr[100:360,120:590,:])
<matplotlib.image.AxesImage at 0xb2f6d30>

png

四、ndarray的聚合操作

1. 求和np.sum

a1
array([[25, 22,  9, 67, 23],
       [27, 37, 57, 83, 38],
       [ 8, 32, 34, 10, 23],
       [15, 87, 25, 71, 92]])
a1.sum(axis=0)
array([ 75, 178, 125, 231, 176])

2. 最大最小值:np.max/ np.min

同理

3.平均值:np.mean()

3. 其他聚合操作

Function Name	NaN-safe Version	Description
np.sum	np.nansum	Compute sum of elements
np.prod	np.nanprod	Compute product of elements
np.mean	np.nanmean	Compute mean of elements
np.std	np.nanstd	Compute standard deviation
np.var	np.nanvar	Compute variance
np.min	np.nanmin	Find minimum value
np.max	np.nanmax	Find maximum value
np.argmin	np.nanargmin	Find index of minimum value
np.argmax	np.nanargmax	Find index of maximum value
np.median	np.nanmedian	Compute median of elements
np.percentile	np.nanpercentile	Compute rank-based statistics of elements
np.any	N/A	Evaluate whether any elements are true
np.all	N/A	Evaluate whether all elements are true
np.power 幂运算

六、ndarray的排序

1. 快速排序

np.sort()与ndarray.sort()都可以,但有区别:

  • np.sort()不改变输入
  • ndarray.sort()本地处理,不占用空间,但改变输入
a1
array([[25, 22,  9, 67, 23],
       [27, 37, 57, 83, 38],
       [ 8, 32, 34, 10, 23],
       [15, 87, 25, 71, 92]])
np.sort(a1,axis=0)
array([[ 8, 22,  9, 10, 23],
       [15, 32, 25, 67, 23],
       [25, 37, 34, 71, 38],
       [27, 87, 57, 83, 92]])
a1.sort(axis=1)
a1
array([[ 9, 22, 23, 25, 67],
       [27, 37, 38, 57, 83],
       [ 8, 10, 23, 32, 34],
       [15, 25, 71, 87, 92]])
posted @ 2019-07-01 16:18  海予心  阅读(84)  评论(0编辑  收藏  举报