本章总结了关于Nuumpy模块的基本用法和常用函数
有详细的注释
import numpy as np
import re
import pandas as pd
arr1 = np.array([1,2,3,4])
print(type(arr1))
arr1.shape
a_list = [1,2,3,4,5]
a_arr2 = np.array(a_list)
print(type(a_list))
print('**'*30)
print(a_arr2.dtype)
print(a_arr2.size)
print(a_arr2.ndim)
print(a_arr2[1:3])
print(a_arr2[-2:])
a_arr3 = np.array([[1,2,3],[2,3,10],[1,34,4]])
print(a_arr3)
print(a_arr3[1,2])
a_arr3[1,2] = 100
print(a_arr3)
print(a_arr3[1:])
print(a_arr3[:,1])
a_arr4 = np.arange(0,100,10)
print(a_arr4)
a_arr5 = np.array([0,1,1,0,0,0,0,0,1,2],dtype=bool)
print(a_arr5)
print(a_arr4[a_arr5])
random_arr = np.random.rand(10)
mask = random_arr > 0.5
print(mask)
print(random_arr[mask])
x = np.array([1,1,1,1,4])
y = np.array([1,1,1,1,5])
print(x == y)
print(np.logical_and(x,y))
print(np.logical_not(x,y))
print(np.logical_or(x,y))
print(np.sum(x))
a_arr3 = np.array([[1,2,3],[2,3,10],[1,34,4]])
print(a_arr3)
print(np.sum(a_arr3,axis=0))
print(a_arr3.prod())
print(a_arr3.min(axis=1))
print(a_arr3.clip(2,4))
"""
解读:比2小的全部变为2,比4大的全部变为4,中间部分不变
"""
a_arr6 = np.array([1.011,2.3145,1.122,4.3122,8.7825],dtype=np.float32)
print(a_arr6.round(decimals=2))
print(a_arr6.argmax())
print(np.sort(a_arr6))
print(np.argsort(a_arr6))
a_arr7 = np.linspace(0,10,10)
values = np.array([2.12,12,1])
print(np.searchsorted(a_arr7,values))
a_arr8 = np.arange(10)
print(a_arr8)
print(a_arr8.shape)
a_arr8.shape = 2,5
print(a_arr8)
a_arr9 = np.arange(10)
a_arr9 = a_arr9[np.newaxis,:]
print(a_arr9.shape)
print(a_arr9.squeeze())
print(a_arr9.flatten())
print(a_arr9.transpose())
a = np.arange(10).reshape((2,5))
b = np.arange(20,30,1).reshape((2,5))
print(np.concatenate((a,b),axis=1))
print('//'*30)
print(np.stack((a,b)))
print(np.vstack((a,b)))
print(np.hstack((a,b)))
print(np.arange(1,10,1,dtype = np.float32).reshape((3,3)))
print(np.logspace(0,1,5))
print(np.r_[0:5:1])
print(np.c_[0:5:1])
print(np.zeros((3,3),dtype=np.int32))
print(np.ones((3,3)))
a = np.empty((3,3))
a.fill(22)
print(a)
print(np.zeros_like(a))
print(np.identity(5))
print(help(np.diag))
print(np.random.rand(3,2))
print(np.random.randint(10,size=(5,4)))
print(np.random.randint(0,10,3))
print(np.random.rand())
print(np.random.normal(0,1,10))
np.set_printoptions(precision=2)
print(np.random.normal(0,1,10))
a_arr10 = np.arange(10)
print(a_arr10)
np.random.shuffle(a_arr10)
print(a_arr10)
np.random.seed(0)
a = np.random.normal(0,1,12).reshape((3,4))
print(a)
def text_save(filename, data):
file = open(filename,'a')
for i in range(len(data)):
s = str(data[i]).replace('[','').replace(']','')
s = s.replace("'",'').replace(',','') +'\n'
file.write(s)
file.close()
print("保存文件成功")
text_save('Ceshi.txt',a)
data = []
with open('Ceshi.txt') as f :
for line in f.readlines():
fileds = line.split()
cur_data = [float(x) for x in fileds]
data.append(cur_data)
data = np.array(data,dtype=np.float32)
print(data)
data = np.loadtxt('Ceshi.txt')
print('-'*30)
print(data)