1 .numpy读取.txt文档
import numpy
aaa = numpy.genfromtxt("aaa.txt", delimiter=" ", dtype=str)
print(type(aaa)) # <class 'numpy.ndarray'>
print(aaa)
seq = aaa[0, 0]
lat = aaa[0, 1]
lon = aaa[0, 2]
chl = aaa[0, 3]
print(seq, lat, lon, chl) # 1 31.45717 120.041978 0.0557
2.用numpy.array构造向量和矩阵
vector = numpy.array([5, 10, 15, 20])使用numpy.array构造向量和矩阵
matrix = numpy.array([[5, 10, 15], [20, 25, 30], [40, 45, 50]])
print(matrix.shape) # (3, 3)
print(vector[0:3]) # [ 5 10 15]
print(matrix[:, 1]) # [10 25 45]
3.numpy限制内部元素属同一类型
numbers = numpy.array([1, 2, 3, 4])
numbers1 = numpy.array([1, 2, 3, 4.0])
numbers2 = numpy.array([1, 2, 3, '4.0'])
print(numbers.dtype) # int32
print(numbers1.dtype) # float64
print(numbers2.dtype) # <U11
print(numbers) # [1 2 3 4]
print(numbers1) # [1. 2. 3. 4.]
print(numbers2) # ['1' '2' '3' '4.0']
你好! 这是你第一次使用 Markdown编辑器 所展示的欢迎页。如果你想学习如何使用Markdown编辑器, 可以仔细阅读这篇文章,了解一下Markdown的基本语法知识。
4.astype
vectors = numpy.array(["1", "2", "3"])
print(vectors.dtype) # <U1
print(vectors) # ['1' '2' '3']
vectors = vectors.astype(float)
print(vectors.dtype) # float64
print(vectors) # [1. 2. 3.]
5.对行/列做运算
print(matrix.sum(axis=1)) # 对行求和 [ 30 75 135]
print(matrix.sum(axis=0)) # 对列求和 [65 80 95]
6.reshape操作
print(numpy.arange(15)) # [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14]
a = numpy.arange(15).reshape(3, 5)
print(a)
"""
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]]
7.pi
from numpy import pi
print(numpy.linspace(0, 2 * pi, 100))
8.数学运算
a = numpy.array([20, 30, 40, 50])
b = numpy.arange(4)
c = a - b #加
d = a + b #减
e = b ** 2 #幂
print(c, d, e) # [20 29 38 47] [20 31 42 53] [0 1 4 9]
A = numpy.array([[1, 0], [2, 2]])
B = numpy.array([[1, 1], [2, 2]])
print(A * B) #对应元素相乘
print(A.dot(B)) # 真正的矩阵相乘
C = np.arange(3)
print(C) # [0 1 2]
print(np.exp(B)) # [1. 2.71828183 7.3890561 ]
print(np.sqrt(B)) # [0. 1. 1.41421356]