Programing Language

Python - Numpy

2021-07-02  本文已影响0人  Hello育种

Numpy是python 进行科学计算的一个核心库。它提供了高维数组目标,和对其进行计算。

# use it
import numpy as np

1 创建array

 np.zeros((3,4)) #Create an array of zeros
 np.ones((2,3,4),dtype=np.int16) #Create an array of ones
 d = np.arange(10,25,5) #Create an array of evenly spaced values (step value)
 np.linspace(0,2,9) #Create an array of evenly spaced values (number of samples)
 e = np.full((2,2),7) #Create a constant array
 f = np.eye(2) #Create a 2X2 identity matrix np.random.random((2,2)) Create an array with random values
 np.empty((3,2))# Create an empty array

2 保存结果

# data
 np.save('my_array', a)
 np.savez('array.npz', a, b)
 np.load('my_array.npy')
# txt 
 np.loadtxt("myfile.txt")
 np.genfromtxt("my_file.csv", delimiter=',')
 np.savetxt("myarray.txt", a, delimiter=" ")

3 查看array

a.shape  #可以看为行数,列数
len(a)  # # 可以看为行数
a.ndim # 可以看为列数
a.size #所有的元素个数
a.dtype  # 查看元素的类型
a.astype(int) # 将a的元素都转为整型

4 运算

 a - b # a 与b必须同列
 a + b
 a/b # 对应元素相除
 a*b  # 对应元素相乘

 np.exp(b) #Exponentiation
 np.sqrt(b) #Square root
 np.sin(a) #Print sines of an array
 np.cos(b) #Element-wise cosine
 np.log(a) #Element-wise natural logarithm
 c = a.dot(b) # 类似矩阵相乘

 a.sum() #Array-wise sum
 a.min() #Array-wise minimum value
 b.max(axis=0) #Maximum value of an array row
 b.cumsum(axis=1) #Cumulative sum of the elements
 a.mean()# Mean
 b.median()# Median
 a.corrcoef() #Correlation coefficient
 np.std(b) #Standard deviation

5 array 操作

#排序
a.sort() #Sort an array
c.sort(axis=0) #Sort the elements of an array's axis
# 转置
c = a.T   # c为a的转置
# 重定型
b.ravel()  # b改成一维
b.reshape(3,3) #将9个元素改为3行,3列
b.resize((2,5))
# 连接
np.append(h,3) #增加h, 3元素
np.concatenate((a,d),axis=0)   # 行连接
np.vstack((a,b))  #列连接

#划分
np.hsplit(a,3) #将a分为3个array
上一篇 下一篇

猜你喜欢

热点阅读