【星海随笔】numpy全总结

import  numpy  as  np

一. numpy 的 array 使用

array = [1,2,3,4]
array = np.array([1,2,3,4])   #转变为了数组,增加了功能
array + 1
#---out---
#array([2, 3, 4, 5])
#运算后只输出,不更改自身
#还可以和其他的列表进行相加,例如下面的列表array1
#但是列表的数量必须一致
#可以通过  len(array)  或者 array.shape 来查看array的数量
#查看array的其中一个值,可以通过 array[数字] 来获得,索引是从 0 开始的
array1 = [1,2,3,4]
array1 + 1
#---out---
#---------------------------------------------------------------------------
#TypeError                                 Traceback (most recent call last)
#<ipython-input-12-20ed89ee23de> in <module>
#----> 1 array1 + 1

#TypeError: can only concatenate list (not "int") to list
print(type(array))

#<class ‘numpy.ndarray’>
#属性是 ndarray

numpy为了底层计算的高效性 会默认要求里面都是同样的类型
不同的时候,会自动默认转换
例如 float 类型都会转换成 字符串

例如:

array = [1,2,3,4,'5']
array = np.array(array)
array

OUT:array([‘1’, ‘2’, ‘3’, ‘4’, ‘5’], dtype=‘<U21’)

test_array.itemsize  #查看占了多少字节。int64 和 int32不同
						#操作系统不同则类型不同 int64 是8 ,int32 是4
array.shape

out:(5,)

#显示了有多少个数字,并且是以数组的形式输出的
例如:array.size 或 np.size(X) 只显示总数,不显示维度 out: 5
使用起来和列表的规则基本相同,索引切片 也是支持的,规则也是左包含,右不包含

二. numpy 多维的使用

test_array = np.array([ [1,2,3],
                      [4,5,6],
                      [7,8,9]])
test_array.shape
#out: (3,3)   这里显示的是3行3列

test_array.size
#out: 9

#多维取值:
test_array[1,1]
#得到第一行 的第一列的值 得到  5

#所有行的第一列
test_array[:,1]

#第0行的,前两列
test_array[0,0:2]

#修改定位的点,例如第一列的第一行
test_array[1,1] = 10

# 想要深度拷贝  ndarray  属性的值, 如果直接 = 则是只是复制了 内存指针。
test_array2 = test_array.copy()

array.fill(0)
#将里面的值都刷新为 0

三. numpy array 的 类型

  1. dtype=object
np.array([array,array2],dtype=object)

array([array([1, 2, 3, 4]), list([10, 20, 30])], dtype=object)

array = np.array([1,2,3,4,'5'])

out: array([‘1’, ‘2’, ‘3’, ‘4’, ‘5’], dtype=‘<U21’)
#默认都转换成了字符串

array = np.array([1,2,3,4,'5'],dtype = np.object)

out: array([1, 2, 3, 4, ‘5’], dtype=object)
#得出的结果是什么都可存了

array * 2 #如果所有类型都有相同的同一个方法,例如字符串也可以*2 , ‘5’ 就变成了 ’55‘, 但是不支持 加法

  1. dtype=bool

array = np.array([1,2,3,4,5],dtype = np.float64)
新版本dtype不能直接写 float64 或者 float32
可以

mask = np.array([0,0,0,2,4,5],dtype=bool)

array([False, False, False, True, True, True])
#大于 0 的都是True

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

out: 4,5,6

bool类型的快速生成:
array支持 > < 判断
例如:

random_array = np.random.rand(10)
random_array > 0.5

out: array([False, True, False, False, False, True, False, False, False,
True])

  1. dtype float
test_array = np.array([1,2,3,4,5],dtype=float)

in : test_array.dtype
out: float64 #每个占用8字节
in: test_array.nbytes
out: 40

  1. 转变类型
test_array.astype(np.float32)

不改变原值,会输出计算后的值

四. array 的计算

  1. 加法
np.sum(test_array,axis=0)
或
test_array.sum(axis=0)

axis=0 #以 X 为轴进行纵列计算
axis=1 #以列为轴 进行 横统计
axis=-1 #相当于最后一个轴

test_array.ndim
#查看数据目前有几个轴
  1. 乘法,乘积
test_array.prod()

out : 720 # 等价于 1 * 2 * 3 * 4 * 5 * 6

test_array.prod(axis=0)

out: array([ 4, 10, 18])

  1. 求最大最小值,索引位,均值
test_array.min(axis=0)

#以 X 为轴,求每列的最小值

test_array.max(axis=0)

#以X为轴,求每列的最大值

test_array.argmin(axis=0)

#以X为轴 ,求每列的最小值的索引位

test_array.mean(axis=0)

#以X为轴,求均值

  1. 求标准差
test_array.std(axis=0)

#以X为轴,求均值

  1. 求方差
test_array.var(axis=0)
  1. 限制级
test_array.clip(2,4)

#小于 2 的数字 都会转换为 2。
#大于 4 的数字 都会转换为 4。

四舍五入, 对小数进行计算

test_array.round()

对小数点后几位,进行精度输出

test_array.round(decimals=1)
  1. 排序

numpy进行排序

test2_array = ([[1.5,1.3,1.8],
               [2.4,1.1,3.5]])
test3_array = np.array(test2_array)
np.sort(test3_array)

out: array([[1.3, 1.5, 1.8],
[1.1, 2.4, 3.5]])

显示排序后,现在的数字的原来的索引是多少

np.argsort(test3_array)

生成数字
np.linspace(0,10,10)
生成数字 从 0 开始,到 10 结束,按规则生成 10 个数字

  1. 指定条件进行排序
test2_array = ([1.5,1.3,1.8],
              [3.2,2.3,1.2],
              [1.5,3.3,3.5],
              [4.1,4.3,1.8])
test3_array = np.array(test2_array)

index = np.lexsort([-1*test3_array[:,0],test3_array[:,2]])
#第三列做升序,在第三列相等的情况下,第一列做降序
index
test4_array = test3_array[index]
test4_array

out:
array([1, 3, 0, 2])
array([[3.2, 2.3, 1.2],
[4.1, 4.3, 1.8],
[1.5, 1.3, 1.8],
[1.5, 3.3, 3.5]])

五.array 多维度操作扩展

  1. 多维度增加,减少,转换
test_array = test_array[: , np.newaxis , np.newaxis]
test_array.shape

增加了空的shape值,空的维度

可以压缩回去。将没用的维度缩减

test_array = test_array.squeeze()
test_array.shape
test_array.T

#行列位置转换

  1. 拼接
test_ALL_array = np.concatenate((a,b))
test_ALL_array

#拼接在一起,将两个相同的数组进行拼接

还可以选择是横着拼或者竖着拼,如下

test_ALL_array = np.concatenate((a,b),axis = 0)
test_ALL_array
#另一种方式
np.vstack((a,b))  #竖着拼
#或者
np.hstack((a,b))  #横着拼
  1. 拉平
a.ravel()
#或者
a.flatten()

六.np核心命令

np.arange(2,20,2, dtype=np.float32)

#从 2 开始到 20 每两个数字一跳

np.linspace(0,10,50)

#从 0 到 10 构建 50 个数字

np.logspace(0,10,5)

#生成大数字

x, y = np.meshgrid(x,y)

#构造网格 , 假如 X 只有3个数字,X会构成3*3的多维数组
#y 同理。 比较像立体

np.r_[0:10:1]

#构造横向量

np.c_[0:10:1]

#构造竖向量

#填充一个3 x 3 的图形

np.ones((3,3))

out:
array([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]])

np.ones((3,3))  *  8
np.ones((3,3),dtype = np.float32) * 8

out:
array([[8., 8., 8.],
[8., 8., 8.],
[8., 8., 8.]], dtype=float32)

随即填充几个值

a = np.empty(10)

array([0.0e+000, 4.9e-324, 9.9e-324, 1.5e-323, 2.0e-323, 2.5e-323,
3.0e-323, 3.5e-323, 4.0e-323, 4.4e-323])

np.zeros_like(a)

array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])

生成中间对称 1 边缘为 0 的 5*5 图形

np.identity(5)

相乘

np.multiply(x,y)

矩阵相乘

np.dot(x,y)

把Y的单维度变成多维
y.shape = (1,2)

把X的单维变成多维 两行1列
x.shape = (2,1)

判断

x = np.array([1,2,1])
y = np.array([[1,2,1],[2,2,2]])
x == y

array([[ True, True, True],
[False, True, False]])

numpy的随机模块

随机生成 2 * 2 的矩阵

np.random.rand(2,2)

生成 int 类型的 10 以内的随机数,大小为 3 * 3

np.random.randint(10, size = (3,3))

设置随机数小数点后有几位

np.set_printoptions(precision = 2) 

0 到 1 直接随机出现30个数字

a = np.random.normal(0,0.1,30)

重新获取随机数字

np.random.shuffle(a)

设定随机数字的时候,可以手动设置随机的种子是多少。
每个种子代表一种确定的随机方法。这样获取的随机数就是一定的了。

np.random.seed(0)
np.random.normal(0,0.1,10)

写入文件

%%writefile test.txt
1 2 3 4 5 6
2 3 4 5 7 8

读 文件 转换成 数组

data = []
with open('test.txt') as f:
    for line in f:
        fileds = line.split()
        cur_data = [float(x) for x in fileds]
        data.append(cur_data)
data = np.array(data)
data

也可以直接loadtxt, 默认是 空格 为分隔符

np.loadtxt('test.txt')

指定分隔符

np.loadtxt('test.txt', delimiter = ',')

读取的时候去掉第一行

np.loadtxt('test.txt', delimiter = ',' , skiprows = 1)

#文件最好和代码放在一起,这样直接打文件名就可以了
#也可以使用哪几列,例如。usecols = (0 , 1, 4)
#指定使用那几列

保存 数组 a 是数组

np.savetxt('test3.txt',a , fmt = '%d')
np.savetxt('test3.txt',a , fmt = '%d' ,delimiter = ',')

保存数组到一个文件

np.savez('testA.txt',a=a ,b=b)

载入文件中的内容

data = np.load('testA.txt.npz')
a = data.keys()
for i in a:
    print(i)
data['a']
#或者
data['b']

一个数组是npy
多个数组是npz

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值