Numpy学习之矩阵、函数、二元运算及数组读写

版权声明:个人博客网站:https://cunyu1943.github.io/, 欢迎访问留言交流,转载请注明出处! https://blog.csdn.net/github_39655029/article/details/84987249

矩阵

# --*--coding:utf-8--*--
import numpy as np
"""
矩阵
"""
# mat(array),将二维数组转化为矩阵
a = np.array([[1,2,4],
              [4, 5, 6],
              [8, 9, 10]])
print('matrix:\n', np.mat(a))
print(np.mat('1,2,4;5,6,9'))

# matrix.I,表示matrix的逆矩阵
print(np.mat(a).I)

# 利用分块创造新矩阵
a = np.array([[4, 8],
              [5, 19]])
b = np.array([[11, 89],
              [49, 29]])
print(np.bmat('a, b;b, a'))

函数

# --*--coding:utf-8--*--
import numpy as np
import matplotlib.pyplot as plt

"""
一般函数
"""
# 正无穷
print('正无穷:', np.inf)
# 负无穷
print('负无穷:', -np.inf)
# 非法值
print('非法值:', np.nan)

"""
向量化函数
"""

# vectorize(function_name),将函数向量化,产生一个新函数
x = np.array([3, 54, 89])
def sinc(x):
    if x == 0.0:
        return 1.0
    else:
        y = np.pi * x
        return np.sin(y) / y

sinc1 = np.vectorize(sinc)
print('向量化:', sinc1(x))

x = np.linspace(-10, 10, 50)
plt.plot(x, sinc1(x))
plt.show()

二元运算

四则运算对应函数
运算符 对应函数
a + b add(a, b)
a - b subtract(a, b)
a * b multiply(a, b)
a / b divide(a, b)
a ** b power(a, b)
a % b remainder(a,b)
比较与逻辑运算
运算符 对应函数
== equal
!= not_equal
> greater
>= greater_equal
< less
<= less_equal
& bitwise_and
/ bitwise_or
^ bitwise_xor
~ invert
>> right_shift
<< left_shift

ufunc对象

# --*--coding:utf-8--*--
import numpy as np

"""
ufunc对象
"""
# reduce方法
# op.reduce(a),将op沿着某个轴应用,使得数组啊的维数降低一维
a = np.array([3, 4, 5, 6, 9])
print(np.add.reduce(a))
print(np.logical_or.reduce(a))

# accumulate方法
# op.accumulate(a),看成保存reduce每一步的结果所形成的数组
print(np.add.accumulate(a))
print(np.logical_or.accumulate(a))

# reduceat方法
# op.reduceat(a, indices),将操作符运用到指定的下标上,返回一个与indices大小相同的数组
indices = np.array([0,3])
print(np.add.reduceat(a, indices))

# outer方法
# op.outer(a, b),对a中每个元素,将op运用到它与b的每一个元素上所得到的结果
b = np.array([2, 3, 4])
print(np.add.outer(a, b))
print(np.logical_or.outer(a, b))

数组读写

# --*--coding:utf-8--*--
import numpy as np

""" 
数组读写
"""
# 空格(制表符)分隔的文本
data = []
with open('file.txt', 'r') as file:
    for line in file:
        fileds = line.split()
        row_data = [float(x) for x in fileds]
        data.append(row_data)

data = np.array(data)
print('空格分隔:', data)

# 逗号分隔文件
data = np.loadtxt('file1.txt', delimiter=',')
print('逗号分隔:', data)

# 数组写入文件
np.savetxt('out.txt', data)
with open('out.txt') as f:
    for line in f:
        print(line)

"""
Numpy二进制格式
保存的方法:
    1、save(file, arr) 保存单个数组,.npy 格式
    2、savez(file, *args, **kwds) 保存多个数组,无压缩的 .npz 格式
    3、savez_compressed(file, *args, **kwds) 保存多个数组,有压缩的 .npz 格式
读取的方法:
    load(file, mmap_mode=None) 对于 .npy,返回保存的数组,对于 .npz,返回一个{名称-数组}对组成的字典
"""

# 单个数组的读写
a = np.array([[1,2,4],[9,3,0]])
np.save('file2.txt', a)

# 保存多个数组
b = np.array(100)
np.savez('data.npz', a, b)

猜你喜欢

转载自blog.csdn.net/github_39655029/article/details/84987249