科学计算库——Numpy

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_27124771/article/details/81322588
import numpy
# 读取文件
world_alcohol = numpy.genfromtxt("world_alcohol.txt", delimiter=",")

# 帮助文档
print(help(numpy.genfromtxt))

# 数组/矩阵
# numpy.array 中所有的元素均为相同类型
vector = numpy.array([5, 10, 15, 20])
matrix = numpy.array([[5, 10, 15], [20, 25, 30], [35, 40, 45]])

# 数组/矩阵规格
print(matrix.shape)

# 读取数组/矩阵
print(vector[0:3])
print(matrix[:,1])

# 判断
vector = numpy.array([5, 10, 15, 20])
vector == 10

Out:array([False,  True, False, False], dtype=bool)

# 将布尔值当成索引
equal_to_ten = (vector == 10)
print(equal_to_ten)
print(vector[equal_to_ten])

Out:[False  True False False] [10]

# 与/或
equal_to_ten_or_five = (vector == 10) | (vector == 5)
vector[equal_to_ten_or_five] = 50
print(vector)

Out:[50 50 15 20]

# 类型转换
vector = numpy.array(["1", "2", "3"])
print(vector.dtype)
print(vector)
vector = vector.astype(float)
print(vector.dtype)
print(vector)

Out:|S1
['1' '2' '3']
float64
[ 1.  2.  3.]

# 求极值
vector = numpy.array([5, 10, 15, 20])
vector.sum()

# 求和
matrix = numpy.array([
                [5, 10, 15], 
                [20, 25, 30],
                [35, 40, 45]
             ])
matrix.sum(axis=1) # 1-按行求和 0-案列求和

Out:array([ 30,  75, 120])

# 矩阵信息
import numpy as np
a = np.arange(15).reshape(3, 5)

Out:array([[ 0,  1,  2,  3,  4],
            [ 5,  6,  7,  8,  9],
            [10, 11, 12, 13, 14]])

a.shape # out:(3,5)
a.nidm # 维度 out:2
a.dtype.name # 类型 out:'int32'
a.size # 大小 out:15

# 初始化矩阵
np.zeros((3,4))
np.ones((2,3,4), dtype=np.int32)

# 初始化序列
from numpy import pi
np.arange( 10, 30, 5 ) # 从10到30,间隔为5
np.linspace( 0, 2*pi, 100 ) # 从0到2*pi,生成100个数

# 随机值 取值为0-1
np.random.random((2,3))

Out:array([[ 0.40130659,  0.45452825,  0.79776512],
           [ 0.63220592,  0.74591134,  0.64130737]])

# 矩阵乘法
A = np.array( [[1,1],
               [0,1]] )
B = np.array( [[2,0],
               [3,4]] )
A*B # 对应位置相乘
A.dot(B) # 矩阵点乘
np.dot(A,B) # 矩阵点乘   

# 幂运算/开方
B = np.arange(3)
np.exp(B)
np.sqrt(B)

# 矩阵变换
a = np.floor(10*np.random.random((3,4)))
a.ravel() # 将矩阵拉成向量
a.shape = (6, 2) # 变换
a.T # 转置
a.reshape(3,-1) # 最后一位是-1可自动计算

# 矩阵拼接
a = np.floor(10*np.random.random((2,2)))
b = np.floor(10*np.random.random((2,2)))
np.hstack((a,b)) # 横着拼接
np.vstack((a,b)) # 竖着拼接

# 矩阵切分
a = np.floor(10*np.random.random((2,12)))
np.hsplit(a,3) # 横着切分
np.hsplit(a,(3,4)) # 指定切分位置,3和4的位置各切一刀

## 赋值
# 1、a与b指向同一块内存
a = np.arange(12)
b = a
b is a # True
# 2、浅赋值,虽然a与c不指向同一块内存,但他们共用同样的值,如果其中一个内容改变,另一个也会改变
c = a.view()
c is a # False
# 3、深赋值,没有任何关系
d = a.copy() 
d is a # False

# 索引
data = np.sin(np.arange(20)).reshape(5,4)
ind = data.argmax(axis=0) # 每一列最大元素的索引
data_max = data[ind, range(data.shape[1])] # 通过索引取数据取出每个最大值

# 扩展
a = np.arange(0, 40, 10)
b = np.tile(a, (3, 5)) 

# 排序
a = np.array([[4, 3, 5], [1, 2, 1]])
b = np.sort(a, axis=1) # Out:[[3,4,5] [1,2,1]]

a = np.array([4, 3, 1, 2])
j = np.argsort(a) # 排序的元素索引

猜你喜欢

转载自blog.csdn.net/qq_27124771/article/details/81322588