python学习——numpy
numpy学习
In [15]:
import numpy as np
In [16]:
np.__version__
Out[16]:
In [17]:
#pyplot 显示画图,数据分析与可视化
import matplotlib.pyplot as plt
In [18]:
cat = plt.imread('111.jpg')
In [19]:
type(cat)
Out[19]:
In [20]:
cat2 = cat - 15
plt.imshow(cat2)
plt.show()
一、创建ndarray
In [30]:
n1 = np.array([3,1,4,5])
n1
Out[30]:
In [31]:
n2 = np.array([[2,3,4,5],[4,5,6,2],[3,5,2,4]])
n2
Out[31]:
In [32]:
n2.shape
Out[32]:
In [34]:
n1.shape
Out[34]:
In [35]:
#任何一张2维的图片转化成数据3维数组,长宽,最后为颜色
cat.shape
Out[35]:
In [38]:
n3 = np.array(list('ABC'))
n3
Out[38]:
In [39]:
type(n3)
Out[39]:
numpy默认ndarray的所有元素类型是相同的
如果传进来的列表中包含不同的类型,则统一为同一类型,优先级:str>float>int
In [41]:
n4 = np.array([1,2,14,'python'])
n4
Out[41]:
2.使用np的routines函数创建
包含以下常见创建方法:
1) np.ones(shape, dtype=None, order='C')
In [42]:
#1
np.ones(shape=(10,8),dtype=int)
Out[42]:
In [45]:
ones = np.ones(shape=(100,80,3),dtype=float)
plt.imshow(ones)
plt.show()
In [46]:
#2
np.zeros((4,4))
Out[46]:
In [47]:
#3
np.full((10,10),1024)
Out[47]:
In [49]:
#4 np.eye()满秩矩阵-没法进行运算
#x + y = 10
#2x + 2Y = 20
#[[1 1],[2 2]]
np.eye(10)
Out[49]:
In [12]:
#5 lin = linear线性 创建等差数列
import numpy as np
np.linspace(0,100,20,endpoint=False)
Out[12]:
In [4]:
#6 np.arange([start, ]stop, [step, ]dtype=None)
np.arange(0,100,5)
Out[4]:
In [57]:
# 左闭右开
np.arange(0,10,50)
Out[57]:
In [63]:
#7 随机数
np.random.randint(0,150,5)
Out[63]:
In [68]:
#8 正态分布
np.random.randn(100)
Out[68]:
In [71]:
np.random.normal(175,10,100)
Out[71]:
In [73]:
#9 生成0到1的随机数,左闭右开
np.random.random(100)
Out[73]:
In [79]:
#随机生成一张图片
r = np.random.random((200,300,3))
plt.imshow(r)
plt.show()
二、ndarray的属性
4个必记参数: ndim:维度 shape:形状(各维度的长度) size:总长度 dtype:元素类型
In [21]:
cat.ndim
Out[21]:
In [22]:
cat.shape
Out[22]:
In [23]:
cat.size
Out[23]:
In [24]:
cat.dtype
Out[24]:
三、ndarray的基本操作
1.索引
与列表完全一致
In [85]:
n1 = np.random.randint(0,100,(3,4,5))
n1
Out[85]:
In [86]:
n1[0,0,1]
Out[86]:
2.切片
切片时左闭右开
In [89]:
n2 = np.random.randint(150,size=10)
n2
Out[89]:
In [91]:
n2[:5]
Out[91]:
In [92]:
n1.shape
Out[92]:
In [103]:
n1[0:2,1:3,-2:]
Out[103]:
将数据反转
In [27]:
n3 = np.arange(0,10,1)
n3
Out[27]:
In [29]:
n3[::-1]
Out[29]:
In [28]:
n3[::-2]
Out[28]:
3.变形
使用reshape函数,注意参数是一个tuple
In [112]:
n3.shape
Out[112]:
In [113]:
n3.reshape((5,2))
Out[113]:
In [116]:
# 上面图片111.jpg 进行reshape
cat.shape
Out[116]:
In [117]:
cat.reshape(576*1024*3)
Out[117]:
In [118]:
#如果是复数直接转换成一维数组ndarray
cat.reshape(-1)
Out[118]:
4.级联
1.np.concatenate()级联需要注意:
2.级联的参数是列表:一定要加中括号或小括号
3.维度必须相同
4.形状相符
5.重点:级联的方向默认是shape这个tuple的第一个值锁代表的维度方向
6.可通过axis参数改变级联的方向
In [121]:
n1 = np.random.randint(0,10,size=(5,5))
n1
Out[121]:
In [124]:
n1.ndim#查看维度
Out[124]:
In [123]:
np.concatenate((n1,n1),axis=0)
Out[123]:
In [125]:
np.concatenate((n1,n1),axis=1)
Out[125]:
In [127]:
plt.imshow(cat)
plt.show()
In [128]:
cats = np.concatenate((cat,cat))
In [129]:
plt.imshow(cats)
plt.show()
np.hstack与np.vstack 水平级联与垂直级联,处理自己,进行纬度的变更
In [130]:
n2
Out[130]:
In [131]:
#vertical 垂直
n3 = np.vstack(n2)
Out[131]:
In [133]:
n4 = np.array([[2,3,4,5,6,7],[4,5,6,7,8,9]])
np.hstack(n4)
Out[133]:
In [135]:
np.hstack(np.hstack(cat))
Out[135]:
切分
与级联类似,三个函数完成切分工作:
1.np.split axis=0默认切分行;axis=1默认切分列
2.np.vsplit竖直方向切分的是行
3.np.hsplit
In [136]:
cat.shape
Out[136]:
In [30]:
n5 = np.random.randint(0,150,size=(5,7))
n5
Out[30]:
In [143]:
np.split(n5,(1,3))
Out[143]:
In [144]:
np.split(n5,(1,3))[0]
Out[144]:
In [145]:
cat2 = np.split(cat,(200,350))[1]
plt.imshow(cat2)
plt.show()
In [146]:
# axis=0默认切分行
# axis=1默认切分列
np.split(n5,(1,3),axis=1)
Out[146]:
In [147]:
#v 竖直方向切分的是行
np.vsplit(n5,(1,3))
Out[147]:
In [148]:
np.hsplit(n5,(1,3))
Out[148]:
6.副本
所有赋值运算不会为ndarray的任何元素创建副本。对赋值后的对象的操作也对原来的对象生效。
In [152]:
l = [1,2,3,4]
n = np.array(l)
n
Out[152]:
In [157]:
n[2] = 512
n,l
Out[157]:
In [164]:
#当我们的数据是ndarray时,如果我们用=赋值,内存没有改变
n2 = n
print(n2,n)
可以使用copy()函数创建副本
In [163]:
n3 = n.copy()
n3[0] = 1024
print(n3,n)
四、ndarray的聚合操作
1.求和np.sum
In [167]:
#cat求最大值、最小值:display和print相同都可展示内容
print(cat.max(),cat.min())
display(cat.max(),cat.min())
In [187]:
#(4,4,4) ==0, 1, 2
n = np.random.randint(0,150,size=(4,4,4))
n
Out[187]:
In [202]:
#0 代表行每个数组对应位置
n.max(axis=0)
Out[202]:
In [204]:
#1 代表大数组下一层数组
n.max(axis=1)
Out[204]:
In [205]:
#2 代表大数组下两层数组
n.max(axis=2)
Out[205]:
2.求平均值np.mean() 、求和np.sum()
In [206]:
np.mean(n,axis=0)
Out[206]:
In [207]:
np.sum(n,axis=0)
Out[207]:
np.std方差/标准差
np.argmax最大值索引
In [222]:
import numpy as np
n = np.random.randint(0,100,size=10)
print(n)
n.argmin()
Out[222]:
In [225]:
np.argmin(n)
Out[225]:
In [234]:
index = np.argwhere(n>50)
index
Out[234]:
In [235]:
n[index]
Out[235]:
In [237]:
n[np.array([[0],[1]])]
Out[237]:
操作文件
使用pandas打开文件 获取文件中的数据
In [241]:
import pandas as pd
df = pd.read_csv('../data/president_heights.csv')
df
Out[241]:
In [246]:
df.values
Out[246]:
五、ndarray的矩阵操作
1.基本矩阵操作
1)算数运算符:
·加减乘除
In [247]:
import numpy as np
In [248]:
n = np.random.randint(0,10,size=(4,5))
n
Out[248]:
In [249]:
n+10
Out[249]:
In [251]:
n2 = n/2
n2
Out[251]:
In [252]:
np.add(n,n)
Out[252]:
2)矩阵积np.dot()
In [254]:
n1 = np.random.randint(0,10,(2,3))
n2 = np.random.randint(0,10,(3,2))
display(n1,n2)
In [255]:
np.dot(n1,n2)
Out[255]:
In [257]:
np.dot(n2,n1)
Out[257]:
2.广播机制
【重要】ndarray广播机制的两条规则
规则1:为缺失维度补1
规则2:假定缺失元素用已有值填充
In [ ]:
例1:m = np.ones((2,3)) a = np.arange(3) 求m + a
In [260]:
m = np.ones((2,3))
a = np.arange(3)
print(m,a)
display(m,a)
In [261]:
#numpy的广播机制,维度不对应,自动进行不全
m + a
Out[261]:
In [ ]:
例2:a = np.arange(3).reshape((3,1)) b = np.arange(3) 求a+b
In [262]:
a = np.arange(3).reshape((3,1))
b = np.arange(3)
display(a,b)
In [263]:
a + b
Out[263]:
六、ndarray的排序
小测试: 使用以上所学numpy的知识,对一个ndarray对象进行选择排序 def sort(x): 代码越短越好
In [275]:
n1 = np.array([2,5,1,7,4])
In [265]:
n1.size
Out[265]:
In [266]:
#冒泡排序
def sort(nd):
for i in range(nd.size):
for j in range(i,nd.size):
if nd[i]>nd[j]:
nd[i],nd[j] = nd[j],nd[i]
return nd
In [271]:
sort(n1)
Out[271]:
In [281]:
#为了降低运算的空间和时间复杂度,用一层for实现冒泡排序
def sortd(nd):
for i in range(nd.size):
#切片,索引不对应
min_index = np.argmin(nd[i:]) + i
nd[i],nd[min_index] = nd[min_index],nd[i]
return nd
In [282]:
sortd(n1)
Out[282]:
1.快速排序
np.sort()与ndarray.sort()都可以,但有区别:
·np.sort()不改变输入
·ndarray.sort()本地处理,不占用空间,但改变输入
In [287]:
n1 = np.random.randint(0,150,10)
n1
Out[287]:
In [294]:
#使用ndarray.sort(),原来的数据进行了改变,不占用内存
n1.sort()
n1
Out[294]:
In [292]:
n2 = np.sort(n1)
display(n2,n1)
2.部分排序
np.partition(a,k)
有时候我们不是对全部数据感兴趣,我们可能只对最小或最大的一部分感兴趣。
当k为正时,我们想要得到最小的k个数
当k为负时,我们想要得到最大的k个数
In [296]:
nd = np.random.randint(0,150,20)
nd
Out[296]:
In [297]:
np.partition(nd,-5)
Out[297]:
In [298]:
np.partition(nd,5)
Out[298]: