【星海随笔】numpy简单应用

【星海随笔】numpy简单应用,第1张

import numpy as np

生成10到50的数字,并倒序排列

np.arange(10,50)[::-1]

去掉索引为 0 的值,并打印

np.nonzero(a)

在数组的四周填充一圈 0

np.pad(a,pad_width = 1, mode = 'constant' ,constant_values = 0)

out:
array([[0., 0., 0., 0., 0., 0., 0.],
[0., 1., 1., 1., 1., 1., 0.],
[0., 1., 1., 1., 1., 1., 0.],
[0., 1., 1., 1., 1., 1., 0.],
[0., 1., 1., 1., 1., 1., 0.],
[0., 1., 1., 1., 1., 1., 0.],
[0., 0., 0., 0., 0., 0., 0.]])
找到 索引为 100 的位置

np.unravel_index(100,(6,7,8))

np 实现归一化

test_max = b.max()
test_min = b.min()
test_array = (b - test_min)/(test_max - test_min)
test_array

找两个数组中的共有值

np.intersect1d(t1,t2)

python打印时间,显示今天

np.datetime64('today','D')
#支持时间的加减法,下面的显示的是昨天
np.datetime64('today','D') - 1

得到一个月的所有天

np.arange('2017-10','2017-11',dtype='datetime64[D]')

得到一个数的整数部分

np.floor(b)

构建一个数组,让他不能被改变

a = np.zeros(5)
a.flags.writeable = False

read-only

数据比较多,省略的部分也打印

np.set_printoptions(threshold=np.nan)
z = np.zero((15,15))
z

np.set_printoptions(threshold=9)
#需要先做限制

数组b中距离 数字b 距离最小的数的索引

(np.abs(b1-b)).argmin()

将 int 型转换为 float 型

z.astype(np.float32)

生成一个 3 * 3 的矩阵

np.arange(9).reshape(3,3)

遍历数组中的 index 和 value

a = np.ndenumerate(p)
for index,value in a:
    print(index,value)

按照第一列进行排序

#生成数据
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([test3_array[:,0]])
test4_array = test3_array[index]
第二种方法
test3_array[test3_array[:,0].argsort()]

计算每个值的数量

np.bincount(z)

求每个数组的和

a = np.random.randint(0,10,(4,4,4,4))
res = a.sum(axis=(-2,-1))

交换矩阵的两行

p[[0,1]] = p[[1,0]]

计算最常出现的值

z = np.random.randint(0,10,50)
np.bincount(z).argmax()

计算出最大的几个数字

z[np.argpartition[-z,5][:5]

显示所有的数字

import sys
np.set_printoptions(threshold=sys.maxsize)
test4_array = np.random.randint(0,3,(10,3))
test4_array

判断每一行的值是否有重复的

np.any(test4_array[:,1:] == test4_array[:,:-1] ,axis = 1)

判断每一行的值是否全部重复

np.all(test4_array[:,1:] == test4_array[:,:-1] ,axis = 1)

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/904592.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-15
下一篇2022-05-15

发表评论

登录后才能评论

评论列表(0条)

    保存