import numpy as np
a= np.array([2,3,4,5,6],dtype=float)print(a)
a = np.zeros((4,3,4))# 四个全为0的三行四列的数组
b = np.ones((4,3,4))# 四个全为1的三行四列的数组
c = np.empty((4,3,4))# 四个初始内容随机且取决于内存状态的数组的三行四列的数组print(c,type(c)),
打印数组、
a = np.arange(6)# 一维数组print(a)# # 二维数组
b = np.arange(12).reshape(4,3)# 从0-11的四行三咧的二维数组print(b)# # 三维数组
c = np.arange(24).reshape(2,6,2)# 三维打印为矩阵列表print(c)# # 数组太大无法全部打印,省略中心。,只打印角落
d = np.arange(10000).reshape(100,100)print(d)
数组的算数运算
a = np.array([20,30,40,50])
b = np.arange(4)
c = a-b # 重新创建一个数组,把结果填充print(c)
d = b**2# 数组中元素的平方print(b)# [0 1 2 3]print(d)# [0 1 4 9]
矩阵运算
a = np.arange(6).reshape(3,2)print(a)# [[0 1][2 3][4 5]]
b = np.arange(6).reshape(3,2)print(b)
c = a*b # *是元素进行运算print(c)
@ 和 dot来执行矩阵乘积
d = a.dot(b)print(d)
索引 切片 迭代
a = np.arange(10)print(a)# [0 1 2 3 4 5 6 7 8 9]print(a[3])# 3print(a[::-1])# [9 8 7 6 5 4 3 2 1 0] reversed a 列表的翻转print(a[2:6])# [2 3 4 5]##deff(x, y):return10* x + y
b = np.fromfunction(f,(5,4), dtype=int)for row in b:# 迭代多维数组是相对于第一个轴完成的print(row)for element in b.flat:# 如果要对数组中的每个元素执行操作,可以使用flat属性,它是数组所有元素的迭代器print(element)# 查看环境变量# import os# print("PYTHONPATH:", os.environ.get('PYTHONPATH'))# print("PATH:", os.environ.get('PATH'))
改变数组的形状
a = np.arange(12).reshape(3,4)print(a)
b = a.shape
print(b)print(a.ravel())print(a.reshape(6,2))print(a.T)# 三行四列变为四行三列
a.resize((2,6))# 修改数组本身print(a)# a = range(100)# print(a[2 - 3]) # 2-3=-1 相当于a[-1]# print(a[-1])# a[-3]# a[2:13]# a[:3]# a[2-3]
多个数组可以沿不同的轴堆叠在一起
from numpy.random._examples.numba.extending import rg
a=np.floor(10*rg.random((2,2)))print(a)
b = np.floor(10*rg.random((2,2)))print(b)print(np.vstack((a, b)))# 垂直堆叠print(np.hstack((a, b)))# 水平堆叠
column_stack函数将一维数组作为列堆叠到二维数组中
print(np.column_stack((a, b)))# 它等效于hstack仅用于 2D 数组
a = np.floor(10* rg.random((2,12)))print(a)print(np.hsplit(a,3))# 吧a 分成三分# #在第三列和第四列后面拆分“a”print(np.hsplit(a,(3,4)))
简单赋值不会复制对象或其数据。
a = np.array([[1,2,3,4,5,6],[7,8,9,10,11,12],[13,14,15,16,17,18]])
b = a
print(b is a)# true
绘制图像
直线图
import numpy as np
from datetime import datetime
defdmy2ymd(dmy):
dmy =str(dmy,encoding="utf-8")
time = datetime.strptime(dmy,"%d-%m-%Y").date()
t = time.strftime("%Y-%m-%d")return t
dates,opening_prices,highest_prices,lowest_prices,close_prices=np.loadtxt(fname="da_data/aapl.csv",delimiter=",",usecols=(1,3,4,5,6),dtype="M8[D],f8,f8,f8,f8",unpack=True,converters={1:dmy2ymd})# print(res)#绘制直线图from matplotlib import pyplot as plt
from matplotlib import dates as dts
plt.figure("AAPL",facecolor="lightgray")
plt.title("AAPL",fontsize=20)
plt.xlabel("Date",fontsize=14)
plt.ylabel("closing price",fontsize =14)
plt.grid(linestyle=":")#拿到坐标轴
ax = plt.gca()#设置主刻度定位器为周定位器(每周一显示主刻度文本)
ax.xaxis.set_major_locator( dts.WeekdayLocator(byweekday=dts.MO))
ax.xaxis.set_major_formatter(dts.DateFormatter('%d %b %Y'))#设置次刻度定位器为日定位器
ax.xaxis.set_minor_locator(dts.DayLocator())
plt.tick_params(labelsize=8)
dates = dates.astype(dts.datetime.datetime)
plt.plot(dates, opening_prices, color='dodgerblue',
linestyle='-')
plt.gcf().autofmt_xdate()
plt.show()
k线图
import numpy as np
from datetime import datetime
defdmy2ymd(dmy):
dmy =str(dmy,encoding="utf-8")
time = datetime.strptime(dmy,"%d-%m-%Y").date()
t = time.strftime("%Y-%m-%d")return t
dates,opening_prices,highest_prices,lowest_prices,close_prices=np.loadtxt(fname="da_data/aapl.csv",delimiter=",",usecols=(1,3,4,5,6),dtype="M8[D],f8,f8,f8,f8",unpack=True,converters={1:dmy2ymd})# print(res)#绘制直线图from matplotlib import pyplot as plt
from matplotlib import dates as dts
plt.figure("AAPL",facecolor="lightgray")
plt.title("AAPL",fontsize=20)
plt.xlabel("Date",fontsize=14)
plt.ylabel("closing price",fontsize =14)
plt.grid(linestyle=":")#拿到坐标轴
ax = plt.gca()#设置主刻度定位器为周定位器(每周一显示主刻度文本)
ax.xaxis.set_major_locator( dts.WeekdayLocator(byweekday=dts.MO))
ax.xaxis.set_major_formatter(dts.DateFormatter('%d %b %Y'))#设置次刻度定位器为日定位器
ax.xaxis.set_minor_locator(dts.DayLocator())
plt.tick_params(labelsize=8)
dates = dates.astype(dts.datetime.datetime)
plt.plot(dates, close_prices, color='dodgerblue',
linestyle='--',linewidth=2,alpha=0.3)#整理颜色
rise = close_prices > opening_prices
# 第一种方法# color = ["red" if c else "green" for c in rise]# print(color)# 第二种利用掩码
color = np.zeros(rise.size,dtype="U5")
color[:]="green"
color[rise]="white"
edgecolor =["red"if c else"green"for c in rise]#绘制实体# plt.bar(dates,close_prices-opening_prices,color=color,linewidth=0.8,bottom=opening_prices,edgecolor="black",zorder=3)
plt.bar(dates,close_prices-opening_prices,linewidth=0.8,color=color,bottom=opening_prices,edgecolor=edgecolor,zorder=3)#绘制影线
plt.vlines(dates,ymin=lowest_prices,ymax=highest_prices,color=edgecolor)
plt.legend()
plt.gcf().autofmt_xdate()
plt.show()