NumPy 是 Python 科学计算的基础包,它专为进行严格的数字处理而产生。
它提供:
它专为进行严格的数字处理而产生。多为很多大型金融公司使用,以及核心的科学计算组织如:Lawrence Livermore,NASA 用其处理一些本来使用 C++,Fortran 或Matlab 等所做的任务。
ndarray 是一个多维的数组对象,具有矢量算术运算能力和复杂的广播能力,并具有执行速度快和节省空间的特点。
ndarray 的一个特点是同构:即其中所有元素的类型必须相同。
import numpy as np
a1 = np.array([1,2,3,4],dtype=np.complex128)
print(a1)
print("数据类型",type(a1)) #打印数组数据类型
print("数组元素数据类型:",a1.dtype) #打印数组元素数据类型
print("数组元素总数:",a1.size) #打印数组尺寸,即数组元素总数
print("数组形状:",a1.shape) #打印数组形状
print("数组的维度数目:",a1.ndim) #打印数组的维度数目
dtype=。。。 可作为参数输入到之后的类型转换新array建立函数中,作为array初始化的参数选择。
import numpy as np
#指定数据 dtype
a = np.array([2,23,4],dtype=np.int)
print(a.dtype)
# int 64
a = np.array([2,23,4],dtype=np.int32)
print(a.dtype)
# int32
a = np.array([2,23,4],dtype=np.float)
print(a.dtype)
# float64
a = np.array([2,23,4],dtype=np.float32)
print(a.dtype)
# float32
a = np.array([1,2,3,4],dtype=np.complex128)
print(a.dtype)
# complex128
import numpy as np
# 通过 ndarray 的 astype() 方法进行强制类型转换
# astype 会创建一份新的数组,即便是指定为同类型也依然如此
# 浮点数转换为整数时小数部分会被舍弃:
a = np.array([2.5,3.1,4.9],dtype=np.float32)
b = a.astype(np.int64)
print(b.dtype)
print(b)
# 如果某字符串类型的数组里的元素全是数字,也可以通过此方法直接转换成数值类型
a = np.array(["2.5","3.1","4.9"],dtype=np.float32)
b = a.astype(np.float64)
print(b.dtype)
print(b)
array函数接受一切序列类型的对象
import numpy as np
list1 = [1,2,3,4,5]
#List转numpy.array:
temp = np.array(list1)
print(temp)
print("数据类型",type(temp)) #打印数组数据类型
print("数组元素数据类型:",temp.dtype) #打印数组元素数据类型
print("数组元素总数:",temp.size) #打印数组尺寸,即数组元素总数
print("数组形状:",temp.shape) #打印数组形状
#numpy.array转List:
arr = temp.tolist()
print(arr)
print("数据类型",type(arr)) #打印数组数据类型
import numpy as np
#创建数组
array = np.array([[1,2,3],[2,3,4]]) #列表转化为矩阵
print(array)
print('number of dim:',array.ndim) # 维度
# number of dim: 2
print('shape :',array.shape) # 行数和列数
# shape : (2, 3)
print('size:',array.size) # 元素个数
# size: 6
zeros() 函数和 ones() 函数这两个函数分别可以创建指定长度或形状的全0或全1的 ndarray 数组
empty() 函数这个函数可以创建一个没有任何具体值的 ndarray 数组,需要注意一点的是,这个函数返回的值不一定是 0,可能是其他未初始化的垃圾值。
import numpy as np
#创建全零数组
a = np.zeros((3,4)) # 数据全为0,3行4列
print('a:',a)
b = np.zeros(a.shape) # 数据全为0,3行4列
print('b:',b)
#创建全一数组, 同时也能指定这些特定数据的 dtype:
a = np.ones((3,4),dtype = np.int) # 数据为1,3行4列
print('a:',a)
b = np.ones(a.shape) # 数据全为0,3行4列
print('b:',b)
#创建全空数组, 其实每个值都是接近于零的数:
a = np.empty((3,4)) # 数据为empty,3行4列
print('a:',a)
b = np.empty(a.shape) # 数据全为0,3行4列
print('b:',b)
import numpy as np
#用 arange 创建连续数组:
a = np.arange(10,20,2) # 10-19 的数据,2步长
print(a)
#使用 reshape 改变数据的形状
a = np.arange(12).reshape((3,4)) # 3行4列,0到11
print(a)
#用 linspace 创建线段型数据:
a = np.linspace(1,10,20) # 开始端1,结束端10,且分割成20个数据,生成线段
print(a)
#同样也能进行 reshape 工作:
a = np.linspace(1,10,20).reshape((5,4)) # 更改shape
print(a)
import numpy as np
#一维索引
A = np.arange(3,15)
print('A = ',A)
print('A[3] = ',A[3]) # 6
#二维
A = np.arange(3,15).reshape((3,4))
print('A = ',A)
print('A[2] = ',A[2])
print('A[2][]2 = ',A[2][2])
print('A[2,2] = ',A[2,2])
print('A[1, 1:3] = ',A[1, 1:3])
print('row = ')
for row in A:
print(row)
print('column = ')
for column in A.T:
print(column)
#flatten是一个展开性质的函数,将多维的矩阵进行展开成1行的数列。而flat是一个迭代器,本身是一个object属性。
print('A.flatten = ',A.flatten())
print('A.flat ===== 所有元素逐个打印')
for item in A.flat:
print(item)
import numpy as np
array1 = np.array([[1,2,3],[2,3,4]]) #列表转化为矩阵
array2 = np.array([[2,3,4],[3,4,5]]) #列表转化为矩阵
# 减法
array3 = array2 - array1
print(array3)
# 加法
array3 = array2 + array1
print(array3)
# 对应元素相乘
array3 = array2 * array1
print(array3)
# 对应元素乘系数
array4 = array1 * 2
print(array4)
# 对应元素次方
array4 = array1 ** 2
print(array4)
# 对应元素正弦
array4 = np.sin(array1)
print(array4)
# 比较符号
array5 = array1>2
print(array5)
# 判断矩阵是否全部为正确
print(array5.all())
# 判断矩阵是否存在正确
print(array5.any())
import numpy as np
arr1=np.array([[1,1],[0,1]])
arr2=np.arange(4).reshape((2,2))# 形变
print(arr1)
print(arr2)
# 点乘运算
arr3 = np.dot(arr1,arr2)
print(arr3)
import numpy as np
A = np.arange(2,14).reshape((3,4))
print("A =",A)
print("sum =",np.sum(A,axis=1))
print("min =",np.min(A,axis=0))
print("max =",np.max(A,axis=1))
print("全矩阵mean =",np.average(A))
print("不同维度mean =",np.average(A,axis=0))
print("全矩阵mean =",np.mean(A))
print("不同维度mean =",np.mean(A,axis=1))
print("中位数 = ",np.median(A)) # 7.5中位数
# argmin() 和 argmax() 两个函数分别对应着求矩阵中最小元素和最大元素的索引。
# 相应的,在矩阵的12个元素中,最小值即2,对应索引0,最大值为13,对应索引为11。
print("最小值索引",np.argmin(A)) # 0
print("最大值索引",np.argmax(A)) # 11
print("累加矩阵 = ",np.cumsum(A)) #累加函数 (返回的是以为数组) 生成的矩阵每一个元素均是从原矩阵首项累加到对应项的元素之和
print("累差矩阵 = ",np.diff(A)) #累差运算函数
x,y = np.nonzero(A) #将所有非零元素的行与列坐标分割开,重构成两个分别关于行和列的矩阵
print("非零行坐标 = ",x)
print("非零列坐标 = ",y)
import numpy as np
A = np.arange(14,2, -1).reshape((3,4))
print("A = ",A)
print("A默认维度排序 = ",np.sort(A))
print("A其他维度排序 = ",np.sort(A,axis = 0))
print("A转置 = ",np.transpose(A)) #转置
print("A转置 = ",A.T)#转置
print("矩阵数值裁剪 = ",np.clip(A,5,9)) #后面的最小值最大值则用于让函数判断矩阵中元素是否有比最小值小的或者比最大值大的元素,并将这些指定的元素转换为最小值或者最大值。
import numpy as np
A = np.array([1,1,1])
B = np.array([2,2,2])
# vertical stack上下合并
C = np.vstack((A,B))
print(C.shape)
print(C)
# horizontal stack左右合并
D = np.hstack((A,B))
print(D.shape)
print(D)
A = np.array([[1,1,1],[1,1,1]])
B = np.array([[2,2,2],[2,2,2]])
C = np.concatenate((A,B,B,A),axis=0)
print("(A,B,B,A),axis=0 = ")
print(C)
D = np.concatenate((A,B,B,A),axis=1)
print("(A,B,B,A),axis=1 = ")
print(D)
import numpy as np
A = np.array([1,1,1])
B = np.concatenate((A,[100])) # 先将p_变成list形式进行拼接,注意输入为一个tuple
C = np.append(B,200) #直接向p_arr里添加p_
#注意一定不要忘记用赋值覆盖原p_arr不然不会变
print(B.shape)
print(B)
print(C.shape)
print(C)
import numpy as np
#这样改变维度的作用往往是将一维的数据转变成一个矩阵,与代码后面的权重矩阵进行相乘, 否则单单的数据是不能呢这样相乘的哦。
A = np.array([1,1,1])
print(type(np.newaxis))
print(np.newaxis==None)#np.newaxis 在使用和功能上等价于 None
print("A:",A)
print("A.shape:",A.shape)
print("A[np.newaxis,:]:",A[np.newaxis,:])
print("A[np.newaxis,:].shape:",A[np.newaxis,:].shape)
print("A[:,np.newaxis]:",A[:,np.newaxis])
print("A[:,np.newaxis].shape:",A[:,np.newaxis].shape)
print("A[np.newaxis,:,np.newaxis].shape:",A[np.newaxis,:,np.newaxis].shape)
# (3,1)
import numpy as np
# 假设a的shape为[1000,128,128]
a = np.random.rand(1000,128,128)
print(a.shape)
# expand_dims为增加内容为空的维度
b=np.expand_dims(a,axis=0)
print(b.shape)
b=np.expand_dims(a,axis=1)
print(b.shape)
b=np.expand_dims(a,axis=2)
print(b.shape)
b=np.expand_dims(a,axis=3)
print(b.shape)
# squeeze为删除内容为空的维度
c=np.squeeze(b)
print(c.shape)
import numpy as np
A = np.arange(12).reshape((3, 4))
print("A = ")
print(A)
B1,B2 = np.split(A, 2, axis=1)# 返回的是一个列表 里面两个元素分别为切片后的array矩阵
print(np.split(A, 2, axis=1))
print("B1 = ",B1)
print("B2 = ",B2)
C1,C2,C3 = np.split(A, 3, axis=0)
print(np.split(A, 3, axis=0))
print("C1 = ",C1)
print("C2 = ",C2)
print("C3 = ",C3)
import numpy as np
A = np.arange(12).reshape((3, 4))
D1,D2,D3 = np.array_split(A, 3, axis=1)
print(np.array_split(A, 3, axis=1))
print(D1)
print(D2)
print(D3)
E1,E2,E3 = np.vsplit(A, 3) # 纵向切割
print(np.vsplit(A, 3))
print(E1)
print(E2)
print(E3)
F1,F2 = np.hsplit(A, 2) # 水平切割
print(np.hsplit(A, 2))
print(F1)
print(F2)
import numpy as np
a = np.arange(24)
print('a = ',a)
b = a.reshape(2,3,4)
print('reshape = ',b)
# ravel函数 可以将多维数组展平(也就是变回一维)
c = b.ravel()
print('ravel = ',c)
# flatten函数 也是将多维数组展平,与ravel函数的功能相同,不过flatten函数会请求分配内存来保存结果,而ravel函数只是返回数组的一个视图(view)
c = b.flatten()
print('flatten = ',c)
# 这种做法将直接改变所操作的数组
b.shape = (6,4)
print('重新设置形状',b)
# transpose函数 将矩阵进行转置
d = b.transpose()
print("转置 = ",d)
# resize函数 和reshape函数的功能一样,但resize会直接修改所操作的数组
# 并且这一步不可以通过赋值来实现,如下所示
b.resize((2,12))
print('resize重新设置形状',b)
numpy.random.randint(low, high=None, size=None, dtype='l')
作用:生成整型随机数,可以是单个随机数,也可以是多维的随机数构成的数组
参数介绍
low:int 型,随机数的下限
high:int 型,默认为空,给随机数设置个上限,即产生的随机数必须小于high,当此值为空时,函数生成[0,low)区间内的随机数
size:int、或ints、或元组,指明生成的随机数的类型
dtype:可选’int’ ,’int32’,默认为’l’
np.random.randint(4)
>>1
np.random.randint(4,size=4)
>>array([2, 2, 2, 0])
np.random.randint(4,10,size=6)
>>array([7, 9, 7, 8, 6, 9])
np.random.randint(4,10,size=(2,2),dtype='int32')
>>
array([[7, 4],
[6, 9]])
np.random.uniform(low=0.0, high=1.0, size=None)
作用:可以生成[low,high)中的随机数,可以是单个值,也可以是一维数组,也可以是多维数组
参数介绍:
low :float型,或者是数组类型的,默认为0
high:float型,或者是数组类型的,默认为1
size:int型,或元组,默认为空
import numpy as np
np.random.uniform() # 默认为0到1
>>0.827455693512018
np.random.uniform(1,5)
>>2.93533586182789
np.random.uniform(1,5,4) #生成一维数组
>>array([ 3.18487512, 1.40233721, 3.17543152, 4.06933042])
np.random.uniform(1,5,(4,3)) #生成4x3的数组
>>array([[ 2.33083328, 1.592934 , 2.38072 ],
[ 1.07485686, 4.93224857, 1.42584919],
[ 3.2667912 , 4.57868281, 1.53218578],
[ 4.17965117, 3.63912616, 2.83516143]])
np.random.uniform([1,5],[5,10])
>>array([ 2.74315143, 9.4701426 ])
random_sample(size=None)
作用:返回[0,1)之间的浮点型随机数,通过size控制返回的形状
np.random.random_sample()
>>0.47108547995356098
type(np.random.random_sample())
>>
np.random.random_sample((5,))
>>array([ 0.30220482, 0.86820401, 0.1654503 , 0.11659149, 0.54323428])
固定范围和均值的随机数组
Three-by-two array of random numbers from [-5, 0):
5 * np.random.random_sample((3, 2)) - 5
>>array([[-3.99149989, -0.52338984],
[-2.99091858, -0.79479508],
[-1.23204345, -1.75224494]])
rand(d0, d1, …, dn)
作用:返回[0,1)内的浮点数,输入的d0,d1…dn代表维度信息,没有输入时,则返回[0,1)内的一个随机值
np.random.rand()
>>0.9027797355532956
np.random.rand(3,3)
>>
array([[ 0.47507608, 0.64225621, 0.9926529 ],
[ 0.95028412, 0.18413813, 0.91879723],
[ 0.89995217, 0.42356103, 0.81312942]])
np.random.rand(3,3,3)
>>
array([[[ 0.30295904, 0.76346848, 0.33125168],
[ 0.77845927, 0.75020602, 0.84670385],
[ 0.2329741 , 0.65962263, 0.93239286]],
[[ 0.24575304, 0.9019242 , 0.62390674],
[ 0.43663215, 0.93187574, 0.75302239],
[ 0.62658734, 0.01582182, 0.66478944]],
[[ 0.22152418, 0.51664503, 0.41196781],
[ 0.47723318, 0.19248885, 0.29699868],
[ 0.11664651, 0.66718804, 0.39836448]]])
random_integers(low, high=None, size=None)
和randint的用法较为相似,区别在于[low,high]
的右边界能够取到,且改函数即将被抛弃,可以使用
np.random.randint(low,high+1)进行代替
随机数可以分为两大类
一类是浮点型的,常以np.random.uniform为代表,np.random.rand,np.random.radnom和np.random.random_simple可以看作是np.random.uniform的特例;
另一类是整数型的,以np.random.randint为代表,也有np.random.random_integers 但是后者将被前者取代
numpy.sort() 函数返回输入数组的排序副本。函数格式如下:
numpy.sort(a, axis, kind, order)
参数说明:
import numpy as np
a = np.random.randint(0,100,(2,5))
b = np.sort(a,axis = 0)
c = np.sort(a,axis = 1)
d = np.sort(a,axis = 0)[::-1]
e = np.sort(a,axis = 1)[::-1]
print(a)
print(b)
print(c)
print(d)
print(e)
python中找出numpy array数组的最值及其索引
在list列表中,max(list)可以得到list的最大值,list.index(max(list))可以得到最大值对应的索引
但在numpy中的array没有index方法,取而代之的是where,其又是list没有的
首先我们可以得到array在全局和每行每列的最大值(最小值同理)
a = np.arange(9).reshape((3,3))
print(a)
print(np.max(a)) #全局最大
print(np.max(a,axis=0)) #每列最大
print(np.max(a,axis=1)) #每行最大
# 然后用where得到最大值的索引,返回值中,前面的array对应行数,后者对应列数
print(np.where(a==np.max(a)))
print(np.where(a==np.max(a,axis=0)))
# 如果array中有相同的最大值,where会将其位置全部给出
a[1,0]=8
print(a)
print(np.where(a==np.max(a)))
直接使用“==”进行比较
import numpy as np
a = np.array([1,2,3])
b = np.array([1,2,1])
c = (a==b)
print(c)
查看输出结果便变得很麻烦,这时我们可以使用all方法,直接比对a矩阵和b矩阵的所有对应的元素是否相等。
而any()方法是查看两矩阵是否有一个对应元素相等。事实上,all()操作就是对两个矩阵的比对结果再做一次与运算,而any则是做一次或运算
import numpy as np
a = np.array([1,2,3])
b = np.array([1,2,1])
c = (a==b).all()
# 不全都一样所以输出False
print(c)
a = np.array([1,2,3])
b = np.array([1,1,1])
# 有一个一样所以输出True
d = (a==b).any()
print(d)
numpy.around(a, decimals=0, out=None)
Evenly round to the given number of decimals.
a : array_likeInput data.
decimals : int, optionalNumber of decimal places to round to (default: 0). If decimals is negative, it specifies the number of positions to the left of the decimal point.
out : ndarray, optionalAlternative output array in which to place the result. It must have the same shape as the expected output, but the type of the output values will be cast if necessary. See doc.ufuncs
(Section “Output arguments”) for details.
rounded_array : ndarrayAn array of the same type as a, containing the rounded values. Unless out was specified, a new array is created. A reference to the result is returned.The real and imaginary parts of complex numbers are rounded separately. The result of rounding a float is a float.
equivalent method
ceil
, fix
, floor
, rint
, trunc
Notes
For values exactly halfway between rounded decimal values, NumPy rounds to the nearest even value. Thus 1.5 and 2.5 round to 2.0, -0.5 and 0.5 round to 0.0, etc. Results may also be surprising due to the inexact representation of decimal fractions in the IEEE floating point standard [R9] and errors introduced when scaling by powers of ten.
Examples
import numpy as np
# 默认输入的时候 演示out的使用
b = np.zeros(2)
a = np.around([0.37, 1.64],out = b)
print(a)
print(b)
# 保留1位小数
a = np.around([0.37, 1.64], decimals=1)
print(a)
a = np.around([.5, 1.5, 2.5, 3.5, 4.5])
print(a)
# 趋向于最近的整数
a = np.around([1,2,3,11], decimals=1)
print(a)
a = np.around([1,2,3,11], decimals=-1)
print(a)
示例
import numpy as np
l1=np.arange(5)
l2,l3=l1*2,l1*3
np.savetxt('001',(l1,l2,l3))
a=np.loadtxt('001')
print(a)
关于如何保存路径和保持格式
np.savetxt('xxxx/01.txt',a,fmt="%.18f,%.18f",delimiter="\n")
第一个参数可以指定保存的路径以及文件。fmt="%.18f,%.18f"指定保存的文件格式,delimiter="\n"表示分隔符,这两个一起生成的文件格式如下
import numpy as np
a=np.arange(6)
a = a.reshape(3,2)
np.savetxt('./01.txt',a,fmt="%.1f,%.1f",delimiter="\n")
a=np.loadtxt('./01.txt',delimiter=",")
print(a)
loadtxt的详细介绍
savetxt的详细介绍
np.sum(arrayname**2)
import numpy as np
import tensorflow as tf
numpy_test = np.ones(5)
print(numpy_test)
print(numpy_test.shape)
tensor_test = tf.convert_to_tensor(numpy_test)
print(tensor_test)
print(tensor_test.shape)
numpy random 生成随机矩阵
np.random.choice的用法
numpy:np.random.choice的用法
np.random.choice用法中文和样例详解
numpy.linspace使用详解
Numpy 中clip函数的使用
np.max 与 np.maximum
Numpy中stack(),hstack(),vstack()函数详解
【Python数据分析】Numpy的详细教程
numpy&pandas莫烦
首先了解pickle的定义:
pickle: 用于python特有的类型和python的数据类型间进行转换
pickle提供四个功能:dumps,dump,loads,load
pickle可以存储所有python支持的原生类型(bool,int,float,string,byte,none等),由任何原生类型组成的列表、元组、字典和集合,函数、类、类的实例。
所以这个报错本质就是数据文件不一致,numpy的loadtxt()和load()的区别
load()代表用Numpy专用的二进制格式保存数据,它们会自动处理元素类型和形状等信息。一般load读取的是.npy或者.npz的文件。
loadtxt()主要是用来读取txt等文件的
以下是loadtxt()的一般用法,最普通的就是loadtxt(“文件名.txt”)
numpy.loadtxt(fname, dtype=, comments=’#’, delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0)
报错原因是因为用load()直接读取txt文件导致读取不到。改用loadtxt()即可。