
1. 随机生产服从正态分布的sample
sampleNo = 1000
mu = 85
sigma = 4
np.random.seed(0) s = np.random.normal(mu, sigma, sampleNo )
2.两个numpy对应元素相乘再求和
List1 = [1, 2]
List2 = [5, 6]List3 = np.multiply(np.array(List1), np.array(List2))
print(sum(List3.tolist()))
3. 给数组重新设置尺寸。
a = numpy([1,2,3,4])
b = a.reshape(2,2,1)
[[[1] [2]] [[3] [4]]]
4. 产生多维数组并将其值附为0或1。
performance = np.zeros([5,2])
performance = np.ones([5,2])
5. 产生normal分布的数组 X~(0,1)size = 50000*10000
np.random.normal(0,1, size = [50000,10000])
6. 数组除以同一个数。
performance/[5]
7. 数组拼接。
(1)转换成list用list函数拼接
(2)np.append
a=np.arange(5)
np.append(a,10)
array([ 0, 1, 2, 3, 4, 10])
(3) np. concatenate
example for (3)
import numpy as np
lst = [np.array([[[1,2,3],[1,2,3]],[[1,2,3],[1,2,3]]]),np.array([[[1,2,3],[1,2,3]],[[1,2,3],[1,2,3]]]),np.array([[[1,2,3],[1,2,3]],[[1,2,3],[1,2,3]]])]
print(lst[0].shape)
new = np.concatenate(lst, axis=0) # axis =0 表示按照第一维拼接; axis =1表示按照第二维拼接;axis=3表示按照第三维拼接。
print(new.shape)
print(new)
8. 存储多维数组为HDF5格式[1]
import h5pywith h5py.File("c.hdf5", 'w') as f: # 写入的时候是‘w’
f.create_dataset("r1", data=new, compression="gzip", compression_opts=5)
f.create_dataset("r2", data=new2, compression="gzip", compression_opts=5)
with h5py.File("c.hdf5", 'r') as f: # 读取的时候是‘r’
print(f.keys())
a_new = f.get("r1")[:]
print(a_new.shape)
9. 矩阵相乘[2]
星乘表示矩阵内各对应位置相乘,矩阵a*b下标(0,0)=矩阵a下标(0,0) x 矩阵b下标(0,0);
点乘表示求矩阵内积,二维数组称为矩阵积(mastrix product)np.dot(a,b)
10. 矩阵复制。
10.1 np.tile(a, (1,2))
对矩阵a进行复制a次和列复制b次(a,b)
a = np.array([[1],[2],[3]])
print(a.shape)
print(np.tile(a, (1,2)).shape,np.tile(a, (1,2)))
output:
(3, 1)
(3, 2) [[1 1]
[2 2]
[3 3]]
10.2 np.reapt() [3]
11. 分位数
# 引用numpy模块
import numpy as np
#求数组a的中位数
np.median(a)
#求数组a的四分位数
np.percentile(a, [25, 50, 75])
12. np.mean()计算均值[4]
>>> a = np.array([[1, 2], [3, 4]])
>>> np.mean(a) # 将上面二维矩阵的每个元素相加除以元素个数(求平均数)
2.5
>>> np.mean(a, axis=0) # axis=0,计算每一列的均值
array([ 2., 3.])
>>> np.mean(a, axis=1) # 计算每一行的均值
array([ 1.5, 3.5])
13. 从一个list中随机选择指定个数的子list[5]
list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
slice = random.sample(list, 5) #从list中随机获取5个元素,作为一个片断返回
14. 从数组中随机选择子数组[6]
import numpy as np
data=np.random.random(size=10)
data
Out[4]:
array([ 0.21575642, 0.30620622, 0.01454852, 0.46253994, 0.11222712,
0.32893411, 0.11040516, 0.51010326, 0.83162364, 0.84285834])
index_1=np.random.choice(data.shape[0],4,replace=False)
index_1
Out[6]: array([1, 4, 2, 3])
data1=data[index_1]
data1
Out[8]: array([ 0.30620622, 0.11222712, 0.01454852, 0.46253994])
参考
- ^https://www.zhihu.com/question/359323689
- ^https://blog.youkuaiyun.com/like4501/article/details/79753346
- ^https://blog.youkuaiyun.com/qq_36387683/article/details/87710821
- ^https://blog.youkuaiyun.com/chixujohnny/article/details/51106421
- ^https://blog.youkuaiyun.com/liu3237/article/details/48416969
- ^https://blog.youkuaiyun.com/z962013489/article/details/82716443