numpy笔记三(矩阵)

import numpy as np
import matplotlib.pyplot as plt

#字符串创建矩阵
mat = np.mat("1 2 3; 4 5 6; 7 8 9")
print(mat)
#T属性转置矩阵
print(mat.T)
#I属性获得逆矩阵
print(mat.I)
#使用数组创建矩阵
a = np.array([[-2,1],[4,-3]])
mat = np.mat(a)
print(mat)

#使用eye创建单位矩阵
mat = np.eye(2)
print(mat)

#zeros_like创建和参数形状相同但全为0的数组
result = np.zeros_like(a)
print(result)
#flat逐个设置数组元素的值
result.flat = 42;
print(result)


#创建通用函数
def hello(p):
    print("hello:",p)

#创建一个通用函数ufunc,参数为函数名,函数的参数个数,函数返回值个数
ufunc = np.frompyfunc(hello,1,0)
#调用通用函数
ufunc("aaa")


#通用函数的方法,通用函数有四个方法.

a = np.arange(9)
b = np.arange(9)
print(np.add(a,b))

#对数组的reduce计算结果等价于对数组元素求和
print(np.add.reduce(a))
#与reduce方法不同的是,它将存储运算的中间结果并返回
print(np.add.accumulate(a))
#相当于分步reduce,先计算0-5,5-2,2-7,7-末尾。若后面的数字小,只返回前面索引的值
print(np.add.reduceat(a, [0, 5, 2, 7]))
#outer方法返回一个数组,它的秩(rank)等于两个输入数组的秩的和
print(np.add.outer(np.arange(3), a))

输出结果:

[[1 2 3]
 [4 5 6]
 [7 8 9]]
[[1 4 7]
 [2 5 8]
 [3 6 9]]
[[-4.50359963e+15  9.00719925e+15 -4.50359963e+15]
 [ 9.00719925e+15 -1.80143985e+16  9.00719925e+15]
 [-4.50359963e+15  9.00719925e+15 -4.50359963e+15]]
[[-2  1]
 [ 4 -3]]
[[1. 0.]
 [0. 1.]]
[[0 0]
 [0 0]]
[[42 42]
 [42 42]]
hello: aaa
[ 0  2  4  6  8 10 12 14 16]
36
[ 0  1  3  6 10 15 21 28 36]
[10  5 20 15]
[[ 0  1  2  3  4  5  6  7  8]
 [ 1  2  3  4  5  6  7  8  9]
 [ 2  3  4  5  6  7  8  9 10]]
[Finished in 0.8s]

猜你喜欢

转载自blog.csdn.net/maosijunzi/article/details/79546544
今日推荐