关于Python数据分析基础教程:NumPy学习指南(第2版)的numpy学习心得

转载请标明原创地址:https://blog.csdn.net/qq_42121640/article/details/81949454
文中用到的文件地址:https://download.csdn.net/download/qq_42121640/10625025
学习时候做的一些总结,大家随便看看,没整理好,有时间我会不断更新的.
图形的绘制matplotlib
import matplotlib.pyplot as plt

fig = plt.figure(num=1, figsize=(15, 8),dpi=80)
开启一个窗口,同时设置大小,分辨率
不给num时,创建一个新的窗口,并给定一个增长的num,
给num时,若num窗口存在,调用已经存在的窗口,num不存在则创建新的窗口

曲线图plot(水平数组,垂直数组)
plt.plot(x,y)

fig = mp.gcf() # 获得当前figure

fig.subplots_adjust(left=0) # 设置窗口左内边距为0,即左边留白为0。

设置xy轴范围
mp.xlim(x.min(), x.max())
mp.ylim(sin_y.min(), sin_y.max())

格式字符

π   r'$\pi$'
π½  'r'$\frac{\pi}{2}$'
π¾  r'$\frac{3\pi}{4}$'

#定义横向主刻度标签的刻度差为2的倍数。就是隔几个刻度才显示一个标签文本
xmajorLocator = mp.MultipleLocator(2)
ax1 = mp.gca()
ax1.xaxis.set_major_locator(xmajorLocator)
#x坐标轴的网格使用定义的主刻度格式
ax1.xaxis.grid(True, which=’major’)
#去除坐标轴刻度
ax1.set_xticks([])
ax1.set_xticks((-5, -3, -1, 1, 3, 5)) # 设置坐标轴刻度
# 设置刻度的显示文本,rotation旋转角度(正为逆,负为顺),fontsize字体大小
ax1.set_xticklabels(labels=[‘x1’, ‘x2’, ‘x3’, ‘x4’,
‘x5’], rotation=-30, fontsize=’small’)

ax.spines[‘left’].set_position((‘axes’, 0.5))
axes 0-1 设置在指定的轴位置
data 设置在指定的数据坐标处
outward *“向外”:将轴从数据区域中伸出指定数量的点。(负数指定放置
轴内)。

mp.tight_layout() # 紧凑布局

‘mp.NullLocator()’, # 空定位器
‘mp.MaxNLocator(nbins=3, steps=[1, 3, 5, 7, 9])’, # 最大值定位器,最大值3,可选间隔13579
‘mp.FixedLocator(locs=[0, 2.5, 5, 7.5, 10])’, # 固定定位器,
‘mp.AutoLocator()’, # 自动定位器,系统默认的定位器
‘mp.IndexLocator(offset=0.5, base=1.5)’, # 索引定位器,开始,间隔
‘mp.MultipleLocator()’, # 次刻度定位器
‘mp.LinearLocator(numticks=21)’, # 线性均分定位,等分20份
‘mp.LogLocator(base=2, subs=[1.0])’] # 指数定位器,2为底,指数增长量1.0

mp.axis(‘equal’) # xy轴等比,画出来的圆不变形
mp.tick_params(labelsize=10) # 坐标轴上刻度线样式
mp.grid(linestyle=’:’) # 网格线

设置极坐标
mp.gca(projection=’polar’)

mp.gcf().autofmt_xdate()水平坐标轴上的字自适应(倾斜30°)

小结:
图形对象:figure
子图:subplot、GridSpec、axes
刻度定位器:xxxLocator
set_major_locator
set_minor_locator
散点图:scatter
填充:fill_between
条形图:bar
等高线图:contourf/contour
热力图:imshow
饼图:pie
坐标线:grid
极坐标:gca(projection=’polar’)
空间曲面:gca(projection=’3d’)
plot_surface/plot_wireframe
对数坐标:semilogy
简单动画:FuncAnimation

Numpy
1. 创建一种新的异构的数据类型
from numpy import *
t = dtype([(‘name’, str_, 40), (‘numitems’, int32), (‘price’,float32)])
In [15]: t
Out[15]: dtype([(‘name’, ‘

读取股票csv进行k线图绘制

将星期一作为主刻度
ax = mp.gca()
ax.xaxis.set_major_locator(
md.WeekdayLocator(byweekday=md.MO))

[12345] >= 3 ->b [F F T T T]
a = [10 20 30 40 50 ]
a[b] = [30 40 50]
布尔数组,掩码

dates.size

理解
- 算数平均值 对真值的无偏估计 numpy.mean()
- 加权平均值 权重相等时为算数平均值 numpy.average(S,weigts=W)
- 成交量加权平均值VWAP 以成交量为权重计算出来的加权平均值
- 时间加权平均值TWAP 以时间为权重计算出来的加权平均值(对近期的价格给以较高的权重)
- 最大值/最小值 max/min argmax/argmin返回下标 maximum(a,b)/minimum(a,b)生成两个数组对应元素的最大值最小值组成的数组

a = np.random.randint(10, 100, 9).reshape(3, 3)
b = np.random.randint(10, 100, 9).reshape(3, 3)
c, d = np.maximum(a, b), np.minimum(a, b)
print(a,b)
print(c, d, sep='\n')

[[69 35 99]
 [15 95 57]
 [26 13 91]]
[[87 13 30]
 [13 44 36]
 [91 18 48]]
[[87 35 99]
 [15 95 57]
 [91 18 91]]
[[69 13 30]
 [13 44 36]
 [26 13 48]] 
  • ptp 返回数组中最大值和最小值之差(n维)
highest_prices, lowest_prices = np.loadtxt(
'../../data/aapl.csv', delimiter=',',
usecols=(4, 5), unpack=True)
print(np.ptp(highest_prices), np.ptp(lowest_prices))
out:24.86 26.97
  • med中位数
  • std标准差

将星期数据统计出来

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import datetime as dt
import numpy as np


def week1(dmy):
    dmy = str(dmy, encoding='utf-8')
    date = dt.datetime.strptime(dmy, '%d-%m-%Y').date().weekday()
    return date

wdays, closing_prices = np.loadtxt('../data/aapl.csv',
                                   delimiter=',',
                                   usecols=(1, 6),
                                   unpack=True,
                                   converters={1: week1})
print(wdays)

输出:
[ 4. 0. 1. 2. 3. 4. 0. 1. 2. 3. 4. 0. 1. 2. 3. 4. 1. 2. 3. 4. 0. 1. 2. 3. 4. 0. 1. 2. 3. 4.]

np.where(wdays == 1)
返回一个满足条件的下标数组

np.take(数组,下标数组)
返回array数组中由下标数组所指示的数组

数组[掩码数组]
只有与掩码数组中值为True的元素相对应的元素可被访问

字符编码 含义
c单个字符
d 或 i 十进制有符号整数
e 或 E 科学记数法表示的浮点数
f浮点数
g 或 G 自动在 e 、 E 和 f 中选择合适的表示法
o八进制有符号整数
s字符串
u十进制无符号整数
x 或 X 十六进制无符号整数

简单移动均线实例convolve

    # -*- coding: utf-8 -*-
    from __future__ import unicode_literals
    import numpy as np
    # import sys
    from matplotlib.pyplot import plot
    from matplotlib.pyplot import show
    # N = int(sys.argv[1])
    N = 5
    weights = np.ones(N) / N
    print("Weights", weights)
    c = np.loadtxt('../data/aapl.csv', delimiter=',', usecols=(6,), unpack=True)
    print(c)
    # sma = np.convolve(weights, c)[N - 1:-N + 1]  # 有效卷积
    sma1 = np.convolve(weights, c, 'valid')
    # print(sma == sma1)
    print('sma', sma1)
    t = np.arange(N - 1, len(c))  # sma1只有n-1之后才有值
    plot(t, c[N - 1:], lw=1.0)
    plot(t, sma1, lw=2.0)
    show()

猜你喜欢

转载自blog.csdn.net/qq_42121640/article/details/81949454
今日推荐