Numpy入门学习之(五)数组、矩阵中级操作

函数汇总

import numpy as np

# 1. 多维数组

print('=========== 1. 多维数组 ===========')
b = np.arange(24).reshape(2,3,4) #理解为2页,每页上有3行*4列
print('b.shape',b.shape)
print('b')

print(b)

b.shape (2, 3, 4)
b
[[[ 0  1  2  3]
  [ 4  5  6  7]
  [ 8  9 10 11]]

 [[12 13 14 15]
  [16 17 18 19]
  [20 21 22 23]]]

# 可以用三维坐标/切片选择任意页,行号和列号, remember that start with 0
print('b[0,0,0]')
print(b[0,0,0])
b[0,0,0]
0
print('b[0,1,2]') 
print(b[0,1,2]) # 1th page, 2th row,3th column
b[0,1,2]
6
print('b[0,:,:]')
print(b[0,:,:])
b[0,:,:]
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
print('b[1,:2,1:]')
print(b[1,:2,1:])
b[1,:2,1:]
[[13 14 15]
 [17 18 19]]

# 2. 改变数组的维度

# reshape(), ravel() and flatten()
print('=========== 2. 改变数组的维度 ===========')
b = np.arange(24).reshape(2,3,4)
print('b.shape',b.shape)
print('b')
print(b)
b.shape (2, 3, 4)
b
[[[ 0  1  2  3]
  [ 4  5  6  7]
  [ 8  9 10 11]]

 [[12 13 14 15]
  [16 17 18 19]
  [20 21 22 23]]]
print('b.ravel()')
print(b.ravel())
b.ravel()
[ 0  1  2 ..., 21 22 23]

print('b.flatten()')

print(b.flatten())

b.flatten()
[ 0  1  2 ..., 21 22 23]

# flatten 这个函数恰如其名,flatten就是展平的意思,与ravel函数的功能相同。
# 不过,flatten函数会请求分配内存来保存结果,而ravel函数只是返回数组的一个视图(view)



# 3. 用元组设置维度

# 除了可以使用reshape函数,我们也可以直接用一个正整数元组来设置数组的维度
#这样的做法将直接改变所操作的数组,现在数组b成了一个6×4的多维数组
print('=========== 3. 用元组设置维度 ===========')
print(' reshape只返回数组的一个视图与ravel类似,不会对原数组的尺寸进行修改 ')
print('b.reshape(3,-1)')
print(b.reshape(3,-1))
print('b')
print(b)
b.reshape(3,-1)
[[ 0  1  2 ...,  5  6  7]
 [ 8  9 10 ..., 13 14 15]
 [16 17 18 ..., 21 22 23]]
b
[[[ 0  1  2  3]
  [ 4  5  6  7]
  [ 8  9 10 11]]

 [[12 13 14 15]
  [16 17 18 19]
  [20 21 22 23]]]

print('直接设置shape属性为一个新的元组的方式,会修改原始数组')
print('原始b')
print(b)
直接设置shape属性为一个新的元组的方式,会修改原始数组
原始b
[[[ 0  1  2  3]
  [ 4  5  6  7]
  [ 8  9 10 11]]

 [[12 13 14 15]
  [16 17 18 19]
  [20 21 22 23]]]

b.shape = (6,-1) #注意这里一定要用元组
print('b.shape = ',b.shape)
print('The changed b array by assigning a tuple to b.shape')
print(b)
b.shape =  (6, 4)
The changed b array by assigning a tuple to b.shape
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]
 [12 13 14 15]
 [16 17 18 19]
 [20 21 22 23]]

#==============================================================================

#  4. 数组的组合

#  NumPy数组有水平组合、垂直组合和深度组合等多种组合方式
#  使用vstack、dstack、hstack、column_stack、row_stack
#  以及concatenate函数来完成数组的组合

print('=========== 4. 数组的组合 ===========')
a = np.arange(9).reshape(3,3)
b = 2*a 
print('a')
print(a)
print('b')
print(b)
a
[[0 1 2]
 [3 4 5]
 [6 7 8]]
b
[[ 0  2  4]
 [ 6  8 10]
 [12 14 16]]

# # 水平组合

print('np.hstack()')
print( np.hstack((a,b)) )
np.hstack()
[[ 0  1  2  0  2  4]
 [ 3  4  5  6  8 10]
 [ 6  7  8 12 14 16]]

print('np.concatenate((a,b),axis = 0)')
print( np.concatenate((a,b),axis = 0) )
np.concatenate((a,b),axis = 0)
[[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 0  2  4]
 [ 6  8 10]
 [12 14 16]]

# # 垂直组合

print('np.vstack((a,b))')
print( np.vstack((a,b)) )
np.vstack((a,b))
[[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 0  2  4]
 [ 6  8 10]
 [12 14 16]]

print('np.concatenate((a,b),axis = 1)')
print( np.concatenate((a,b),axis=1) )
np.concatenate((a,b),axis = 1)
[[ 0  1  2  0  2  4]
 [ 3  4  5  6  8 10]
 [ 6  7  8 12 14 16]]


c = np.dstack((a,b))###等价于np.concatenate((a,b), axis=2)

print(c.shape)###3维

(3, 3, 2)


# 5. txt文件读写

# 创建一个单位向量并将其存储到文件中(Check tab 'File explorer', and you will find your path)

# 写txt文件

print('=========== 5. 读取文件 ===========')
i3 = np.eye(3)
print(i3)

np.savetxt("eye3.txt",i3)

numpy.eye(N,M=Nonek=0dtype=<type 'float'>)

关注第一个第三个参数就行了

第一个参数:输出方阵(行数=列数)的规模,即行数或列数

第三个参数:默认情况下输出的是对角线全“1”,其余全“0”的方阵,如果k为正整数,则在右上方第k条对角线全“1”其余全“0”,k为负整数则在左下方第k条对角线全“1”其余全“0”。


>>> np.eye(2, dtype=int)    
array([[1, 0],    
       [0, 1]])    
>>>  np.eye(3, k=1)
array([[ 0.,  1.,  0.],    
       [ 0.,  0.,  1.],    
       [ 0.,  0.,  0.]])
np.eye(3, k=-1)
array([[ 0.,  0.,  0.],
       [ 1.,  0.,  0.],
       [ 0.,  1.,  0.]])

# 读txt文件 print('test load file')
ii3 = np.loadtxt("eye3.txt")
print(ii3)

#==============================================================================

#  CSV(comma-separated value, 逗号分割值)文件读写

# 2th column:date,4-th column:每日成交最高价, 5-th column每日成交最低价,6-收盘价,7-成交量
#==============================================================================
# 数据存储在data.csv文件中,我们设置分隔符为,(英文标点逗号),因为我们要
# 处理一个CSV文件。usecols的参数为一个元组,以获取第6字段至第7字段的数据,也就是股票
# 的收盘价和成交量数据。unpack参数设置为True,意思是分拆存储不同列的数据,即分别将收
# 盘价和成交量的数组赋值给变量c和v。
# CSV文件是一种经常用于数据处理的文件格式。我们用loadtxt函数读取了一个包含股价数据
# 的CSV文件,用delimiter参数指定了文件中的分隔符为英文逗号,用usecols中的参数指定了我
# 们感兴趣的数据列,并将unpack参数设置为True使得不同列的数据分开存储,以便随后使用。
#==============================================================================

#6. 读取文件+加权求和与算数平均之间的关系

c,v = np.loadtxt('data.csv',delimiter = ',',usecols=(6, 7), unpack=True)
print('以成交量v作为权重求收盘价的加权平均')


# np.mean与np.average的区别在于average可以进行加权求和,
# 而np.mean只能处理权重均为1时的算术平均值
for i in range(len(c)):
    print('c%d=%f,v%d=%f' %(i,c[i],i,v[i]))
print('weighted average (c is the value list, v is the weight list)')
vwap = np.average(c,weights = v)
print('weighted average of c is ',vwap)
# 算术平均值函数
print('np.mean of c is ',np.mean(c))

# 7. 读取文件找到最大值,最小值、特征列的极差

# 4-th column:每日成交低高价, 5-th column每日成交最高价
print('=========== 7. 读取文件找到最大值,最小值、特征列的极差 ===========')
h,l = np.loadtxt('data.csv',delimiter = ',',usecols = (4,5),unpack = True)
print('The highest value of daily price:', np.max(h))
print('The highest value of daily price:', np.min(l))
print('The middle point between highest value and lowest value:',(np.max(h)+np.min(l))/2)
# ptp函数计算了极差
# 即每维特征最大值和最小值之间的差值     
print('Spread high price',np.ptp(h))
print('Spread low price',np.ptp(l))


# 8. 读取文件+方差、中位数、排序

print('=========== 8. 读取文件+方差、标准差、中位数、排序 ===========')
#求收盘价的中位数
c = np.loadtxt("data.csv",delimiter=',',usecols=(6,),unpack=True)
print('The median of colum 6 is:',np.median(c))#中位数
print('The variance of colum 6 is:',np.var(c))#方差
print('The std of colum 6 is:',np.std(c))#标准差

# np.sort(A) 或者 np,sort(A,axis = 1)行元素升序排列

#np.sort(A,axis = 0) 列元素升序排列

# np.msort()设置死了只能沿着行的方向进行排序,即只能每列元素升序排列

# 9. numpy.where()函数可以根据指定的条件返回所有满足条件的数组元素的索引值

a = np.arange(6)
selected_index = np.where(a>3)
b = a * 2
print(b[selected_index])
#numpy.where()的返回值可以看到,它返回的是满足条件的行号。并且以数组显示出来
[ 8 10]

#==============================================================================

# 专题系列1 - numpy排序

#==============================================================================
print('=========== 专题系列1 - numpy排序 ===========')
# sort(a[, axis, kind, order])-Return a sorted copy of an array.
print('=========== array.sort()改变原来数组元素顺序 ===========')
list1 = [[1,13,2],[3,5,4]]
array = np.array(list1)
array2 = array.copy()

print('Original array:')
print(array)
array.sort(axis = 1)#沿着列的方向进行排序,就是对每行进行排序,这种调用改变array元素顺序
print('Sorted array along axis=1')
print(array)
Original array:
[[ 1 13  2]
 [ 3  5  4]]
Sorted array along axis=1
[[ 1  2 13]
 [ 3  4  5]]
array2.sort(axis=0)
print('Sorted array along axis=0')
print(array2)
Sorted array along axis=0
[[ 1  5  2]
 [ 3 13  4]]

# np.msort() Return a copy of an array sorted along the first axis
print('===========np.sort()不改变原来数组元素顺序,而是返回一个新数组 ===========')
list1 = [[1,13,2],[3,5,4]]
array = np.array(list1)
array2 = array.copy()


print('Original array:')
print(array)
#array.sort(axis = 1)#沿着列的方向进行排序,就是对每行进行排序,这种调用 不 改变array元素顺序
np.sort(array,axis=1) # array = np.sort(array,axis=1)#这样对原始数组覆盖才能修改原数组
print('看看原始数组array是否发生改变?')
print(array)
Original array:
[[ 1 13  2]
 [ 3  5  4]]
看看原始数组array是否发生改变?
[[ 1 13  2]
 [ 3  5  4]]

#array2.sort(axis=0)
np.sort(array,axis = 0)# array = np.sort(array,axis=0)#这样对原始数组覆盖才能修改原数组
#沿着行的方向进行排序,就是对每列进行排序,这种调用 不 改变array元素顺序
print('看看原始数组array是否发生改变?')
print('Sorted array along axis=0')
print(array2)
看看原始数组array是否发生改变?
Sorted array along axis=0
[[ 1 13  2]
 [ 3  5  4]]

print("===========numpy.sort排序都是升序排列,那么如何实现降序排列?===========")
#技巧
list1 = [[1,13,2],[3,5,4]]
array = np.array(list1)
print('原始array')

print(array)

原始array
[[ 1 13  2]
 [ 3  5  4]]

array = -np.sort(-array,axis=1) #对每行降序排列,axis翻译成轴更容易理解
print('每行降序排列的结果')
print(array)
每行降序排列的结果
[[13  2  1]
 [ 5  4  3]]

# 用局部排序的结果(返回排序下表的方法)重新组织整体数组

# mat1=mat1[mat1[:,0].argsort()]
# 注意此种方式不能用于同时根据多个行各自排序情况动态调整,也就是只能循环执行
print('=========== 矩阵按其第一列元素大小顺序来对整个矩阵进行行排序 ===========')
list1 = [[3,13,2],[1,5,4]]
mat1 = np.matrix(list1)
print('Original mat1')
print(mat1)
arg_row_id = np.argsort(mat1[:,0],axis=0)
print('sorted index',arg_row_id)
mat1 = mat1[arg_row_id,:]
print('sorted mat1 according to the first column')
print(mat1)
Original mat1
[[ 3 13  2]
 [ 1  5  4]]
sorted index [[1]
 [0]]
sorted mat1 according to the first column
[[[ 1  5  4]]

 [[ 3 13  2]]]

print('=========== 矩阵按其第一行元素升序顺序来对整个矩阵进行行排序 ===========')
list1 = [[1,3,2], [5,3,4]]
mat1 = np.matrix(list1)
print('Original mat1')
print(mat1)
arg_col_id = np.argsort(mat1[0,:],axis = 1) #默认是升序排列
print('sorted index',arg_col_id)
mat1 = mat1[:,arg_col_id]
print('sorted mat1 according to the first row')
print(mat1)
Original mat1
[[1 3 2]
 [5 3 4]]
sorted index [[0 2 1]]
sorted mat1 according to the first row
[[[1 2 3]]

 [[5 4 3]]]

print('=========== 矩阵按其第一列元素降序顺序来对整个矩阵进行行排序 ===========')
list1 = [[1,13,2],[3,5,-4]]
mat1 = np.matrix(list1)
print('Original mat1')
print(mat1)
arg_row_id = np.argsort(-mat1[:,0],axis=0)
print('sorted index',arg_row_id)
mat1 = mat1[arg_row_id,:]
print('按第一列降序排列')
print(mat1)
Original mat1
[[ 1 13  2]
 [ 3  5 -4]]
sorted index [[1]
 [0]]
按第一列降序排列
[[[ 3  5 -4]]

 [[ 1 13  2]]]

print('=========== 矩阵按其第2行元素降序顺序来对整个矩阵进行行排序 ===========')
list1 = [[1,13,2],[3,5,-4]]
mat1 = np.matrix(list1)
print('Original mat1')
print(mat1)
arg_col_id = np.argsort(-mat1[1,:],axis=1)
print('sorted index',arg_col_id)
mat1 = mat1[:,arg_col_id]
print('按第2行降序排列')
print(mat1)
Original mat1
[[ 1 13  2]
 [ 3  5 -4]]
sorted index [[1 0 2]]
按第2行降序排列
[[[13  1  2]]

 [[ 5  3 -4]]]

#==============================================================================
# 对于一个可迭代的(iterable)/可遍历的对象(如列表、字符串),

# enumerate()是python的内置函数

# enumerate在字典上是枚举、列举的意思
# enumerate将其组成一个索引序列,利用它可以同时获得索引和值
# enumerate多用于在for循环中得到计数
# 例如对于一个seq,得到:(0, seq[0]), (1, seq[1]), (2, seq[2])
#==============================================================================
print('内置函数enumerate介绍') 
list1 = ["这", "是", "一个", "测试"]
for i in range(len(list1)):
    print (i ,list1[i])
内置函数enumerate介绍
0 这
1 是
2 一个
3 测试

for index, item in enumerate(list1):
    print (index, item)
0 这
1 是
2 一个
3 测试

# 多维数组的降序排序

print('多维数组的降序排序')
list1 = [[1, 3, 2], [3, 1, 4]]
a = np.array(list1)
print('original multidimensional array')
print(a)
a = np.array([a[line_id,i] for line_id, i in enumerate(np.argsort(-a, axis=1))])
print('sorted multidimensional array according to multi-column')
print(a)
多维数组的降序排序
original multidimensional array
[[1 3 2]
 [3 1 4]]
sorted multidimensional array according to multi-column
[[3 2 1]
 [4 3 1]]

#==============================================================================

# 专题系列2 - 搜索

#==============================================================================

# 一般numpy数组搜索到某些值后都要进行另外一些操作(如赋值、替换) 

print('简单的逻辑运算,利用布尔值进行检索')
list1 = [1,13,2]
array = np.array(list1)
print('original array:',array)
array[array>2] = -2

print('modified array:',array)

简单的逻辑运算,利用布尔值进行检索
original array: [ 1 13  2]
modified array: [ 1 -2  2]

# 比如替换numpy数组中值为0的元素为1, a[a == 0] = 1
# argmax(a[, axis, out]) Returns the indices of the maximum values along an axis.
list1 = [[1,13,2],[6,5,9]]
array = np.array(list1)
print('original array')
print(array)
i_max = np.argmax(array,axis=0)
print('test argmax')
print(i_max)
original array
[[ 1 13  2]
 [ 6  5  9]]
test argmax
[1 0 1]

# argmin(a[, axis, out])
# Returns the indices of the minimum values along an axis.
list1 = [[1,13,2],[6,5,9]]
array = np.array(list1)
print('original array')
print(array)
i_min = np.argmin(array,axis=0)
print('test argmin')
print(i_min)
original array
[[ 1 13  2]
 [ 6  5  9]]
test argmin
[0 1 0]

# argwhere(a) Find the indices of array elements that are non-zero, 
# grouped by element.
# The output of argwhere is not suitable for indexing arrays. 
# For this purpose use where(a) instead.
print('test argwhere')
x = np.arange(6).reshape(2,3)
print('original x')
print(x)
i_x_where = np.argwhere(x>1)
print('the output of np.argwhere( )')
print(i_x_where)
test argwhere
original x
[[0 1 2]
 [3 4 5]]
the output of np.argwhere( )
[[0 2]
 [1 0]
 [1 1]
 [1 2]]

#==============================================================================

# # 学习np.where()函数

# numpy.where(condition,[x, y])
# Parameters
#     condition : array_like, bool
#         When True, yield x, otherwise yield y.
#     x, y : array_like, optional
#         Values from which to choose. x, y and condition need to be broadcastable to some shape.
# Returns
#     out : ndarray or tuple of ndarrays
#     If both x and y are specified, 
#     the output array contains elements of x where condition is True, 
#     and elements from y elsewhere
#==============================================================================
print('=============Learning np.where()==================')
condition_array = np.array([[True, False], [True, True]])
x = np.array([[1, 2], [3, 4]])
y = np.array([[9, 8], [7, 6]])
print('condition')
print(condition_array)
print('x')
print(x)
print('y')
print(y)
returns_of_where = np.where(condition_array,x,y)
print('returns_of_where')
print(returns_of_where)
=============Learning np.where()==================
condition
[[ True False]
 [ True  True]]
x
[[1 2]
 [3 4]]
y
[[9 8]
 [7 6]]
returns_of_where
[[1 8]
 [3 4]]

print('example 2')
x = np.arange(9.).reshape(3, 3)
row_ids,col_ids = np.where( x > 4 ) #只给出条件,没给三元运算符后面的选项则true返回nonzero
print('行坐标',row_ids)
print('列坐标',col_ids)
x_filter = x[row_ids,col_ids]
print('original x')
print(x)
print('x_filter') # Note: result is 1D. 结果返回一个array(只有一个坐标轴0)
print(x_filter)
example 2
行坐标 [1 2 2 2]
列坐标 [2 0 1 2]
original x
[[ 0.  1.  2.]
 [ 3.  4.  5.]
 [ 6.  7.  8.]]
x_filter
[ 5.  6.  7.  8.]

print('example 3')
x = np.arange(9.).reshape(3, 3)
result = np.where(x < 5, x, -1) #给出条件True或False后面的对应选项,则返回与x同shape的矩阵
print('result when options are given')
print(result)

example 3
result when options are given
[[ 0.  1.  2.]
 [ 3.  4. -1.]
 [-1. -1. -1.]]
#==============================================================================

# matrix 专题

#==============================================================================
# numpy模块中的矩阵对象为numpy.matrix,包括矩阵数据的处理,矩阵的计算,
# 以及基本的统计功能,转置,可逆性等等,包括对复数的处理,均在matrix对象中。 


# 1. 支持字符串赋值,np.array()不支持
#==============================================================================
# 1. class numpy.matrix(data,dtype,copy):返回一个矩阵,其中data为ndarray对象或者字符形式;dtype:为data的type;copy:为bool类型。
# 2. 矩阵的换行必须是用分号(;)隔开,内部数据必须为字符串形式(‘ ’),矩阵的元素之间必须以空格隔开。
# 3. 矩阵中的data可以为数组对象。
#==============================================================================
mat = np.matrix('1 2;3 4') #注意这里不加中括号[]
print(mat)
[[1 2]
 [3 4]]

list = [[1,2],[3,4]]
mat = np.matrix(list)
print(mat)
[[1 2]
 [3 4]]

# matrix的属性值
print(mat.I) # mat的逆矩阵
print(mat.T) # mat的转置
print(mat.dtype)
[[-2.   1. ]
 [ 1.5 -0.5]]
[[1 3]
 [2 4]]
int32

#==============================================================================
# 矩阵对象的属性
# matrix.T      transpose:返回矩阵的转置矩阵
array = np.arange(12).reshape(3,4)
mat = np.matrix(array)
print('mat.T')

print(mat.T)

mat.T
[[ 0  4  8]
 [ 1  5  9]
 [ 2  6 10]
 [ 3  7 11]]

# matrix.H hermitian (conjugate) transpose:返回复数矩阵的共轭元素矩阵(转置+共轭)
print(mat.H)
[[ 0  4  8]
 [ 1  5  9]
 [ 2  6 10]
 [ 3  7 11]]

# matrix.I inverse:返回矩阵的逆矩阵
inv_mat = mat.I
print('mat.I')
print(mat.I)
print('mat.I \'s shape:')
print(inv_mat.shape)
print(mat.shape)
mat.I
[[-0.3375     -0.1         0.1375    ]
 [-0.13333333 -0.03333333  0.06666667]
 [ 0.07083333  0.03333333 -0.00416667]
 [ 0.275       0.1        -0.075     ]]
mat.I 's shape:
(4, 3)
(3, 4)

# matrix.A base array:返回矩阵基于的数组
print('Base array')
print(mat.A) 

print('mat.A1\n',mat.A)

Base array
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
mat.A1
 [[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]


# 矩阵对象的方法:
# all([axis, out]) :沿给定的轴判断矩阵所有元素是否为真(非0即为真)
print(mat.all())#只有零是假,其余全为真
mat[0,0] = -1

print(mat.all())

False
True

# any([axis, out]) :沿给定轴的方向判断矩阵元素是否为真,只要一个元素为真则为真。
print(mat.any()) #有一个非零的就为true
True

# argmax([axis, out]) :沿给定轴的方向返回最大元素的索引(最大元素的位置).
# argmin([axis, out]): 沿给定轴的方向返回最小元素的索引(最小元素的位置)
row_max_all_cols_row_ids = np.argmax(mat,axis=0)
print(row_max_all_cols_row_ids)
row_min_all_cols_row_ids = np.argmin(mat,axis=0)
print(row_min_all_cols_row_ids)


col_max_ids = np.argmax(mat,axis=1)
print(col_max_ids)
col_min_ids = np.argmin(mat,axis=1)
print(col_min_ids)


# argsort([axis, kind, order]) :返回排序后的索引矩阵
# 能够进行整体排序
row_sort_ids = np.argsort(mat,axis = 0)


# diagonal([offset, axis1, axis2]) :返回矩阵中对角线的数据
diag_elements = np.diagonal(mat)
print('mat阵的对角线元素:',diag_elements)
diag_mat = np.diag(diag_elements)
print('mat阵对角线元素构成的对角阵:\n',diag_mat)


mat_sub = mat[:,:-1]
print(np.multiply(mat_sub,diag_mat))
# tolist() :将矩阵转化为列表形式
mat_sub.tofile("back.txt")


trace_mat = mat.trace()
print('mat矩阵对角元素之和',mat.trace())


#==============================================================================

# numpy数学函数专题

#==============================================================================
array = np.arange(12).reshape(3,4)
sin_array = np.sin(array)
print('array:\n',array);
print('sin(array):\n',sin_array)
array:
 [[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
sin(array):
 [[ 0.          0.84147098  0.90929743  0.14112001]
 [-0.7568025  -0.95892427 -0.2794155   0.6569866 ]
 [ 0.98935825  0.41211849 -0.54402111 -0.99999021]]

print('cos(array):\n',np.cos(array))
cos(array):
 [[ 1.          0.54030231 -0.41614684 -0.9899925 ]
 [-0.65364362  0.28366219  0.96017029  0.75390225]
 [-0.14550003 -0.91113026 -0.83907153  0.0044257 ]]

#==============================================================================
# sin(x[, out]) Trigonometric sine, element-wise.
# cos(x[, out]) Cosine element-wise.
# tan(x[, out]) Compute tangent element-wise.
# arcsin(x[, out]) Inverse sine, element-wise.
# arccos(x[, out]) Trigonometric inverse cosine, element-wise.
# arctan(x[, out]) Trigonometric inverse tangent, element-wise.
# hypot(x1, x2[, out]) Given the “legs” of a right triangle, return its hypotenuse.
# arctan2(x1, x2[, out]) Element-wise arc tangent of x1/x2 choosing the quadrant correctly.
# degrees(x[, out]) Convert angles from radians to degrees.
# radians(x[, out]) Convert angles from degrees to radians.
# unwrap(p[, discont, axis]) Unwrap by changing deltas between values to 2*pi complement.
# deg2rad(x[, out]) Convert angles from degrees to radians.
# rad2deg(x[, out]) Convert angles from radians to degrees.
#==============================================================================


#==============================================================================
# Rounding
#==============================================================================
x = np.array([[1.0,2.3],[1.3,2.9]])
print('x\n',x)
print('x.floor\n', np.floor(x))
print('x.ceil\n',np.ceil(x))
print('x.round_\n', np.round_(x)) #看离哪个整数近就靠近哪个整数
print('x.around\n',np.around(x))
x
 [[ 1.   2.3]
 [ 1.3  2.9]]
x.floor
 [[ 1.  2.]
 [ 1.  2.]]
x.ceil
 [[ 1.  3.]
 [ 2.  3.]]
x.round_
 [[ 1.  2.]
 [ 1.  3.]]
x.around
 [[ 1.  2.]
 [ 1.  3.]]

print('exp(x):\n',np.exp(x))
import math
print('自然对数lne=',np.log(math.e))
exp(x):
 [[  2.71828183   9.97418245]
 [  3.66929667  18.17414537]]
自然对数lne= 1.0

# np.unique(x)计算x单一的元素,并对结果排序
x = np.array([9,2,2])
unique_x = np.unique(x)
# setdiff1d(x, y) 差集,在x中但不再y中的集合
y = np.array([2,2,3])
print(np.setdiff1d(x, y))

print(np.intersect1d(x, y))

[9]
[2]

#==============================================================================
# unique(x)计算x单一的元素,并对结果排序
# intersect1d(x, y) 计算x和y相同的元素,并对结果排序
# union1d 结合x和y的元素,并对结果排序
# in1d(x, y) 得到一个布尔数组指示x中的每个元素是否在y中
# setxor1d(x, y) 对称差集,不同时在两个数组中的元素
#==============================================================================

# 求解方程组

#==============================================================================
import numpy as np
A = np.mat("1 -2 1;0 2 -8;-4 5 9")
b = np.array([0, 8, -9])
print('A\n',A)
print('b\n',b)
# AX=b
X = np.linalg.solve(A,b)

print('求解线性方程,结果为X=\n',X)

A
 [[ 1 -2  1]
 [ 0  2 -8]
 [-4  5  9]]
b
 [ 0  8 -9]
求解线性方程,结果为X=
 [ 29.  16.   3.]

#使用array相乘的函数np.dot()验证一下是否成立
print('b=\b',b)
print('check wheter AX equals to b\n',np.dot(A,X))
b [ 0  8 -9]
check wheter AX equals to b
 [[ 0.  8. -9.]]

#==============================================================================

# 特征值和特征向量

#==============================================================================
A = np.mat("3 -2;1 0")
print("A\n",A)
# 调用eigvals函数求解特征
print ("Eigenvalues\n", np.linalg.eigvals(A))
# 使用eig函数求解特征值和特征向量.该函数将返回一个元组,
# 按列排放着特征值和对应的特征向量,其中第一列为特征值,第二列为特征向量
eigenvalues, eigenvectors = np.linalg.eig(A)
print ("First tuple of eig corresponds to eigenvalues\n", eigenvalues)
print ("Second tuple of eig orresponds to eigenvectors\n", eigenvectors)
#使用dot函数验证求得的解是否正确。分别计算等式 Ax = ax 的左半部分和右半部分,
#检查是否相等。

A
 [[ 3 -2]
 [ 1  0]]
Eigenvalues
 [ 2.  1.]
First tuple of eig corresponds to eigenvalues
 [ 2.  1.]
Second tuple of eig orresponds to eigenvectors
 [[ 0.89442719  0.70710678]
 [ 0.4472136   0.70710678]]

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值