通过array转换成numpy格式
import numpy as np
a = [1, 2, 3, 4]
x1 = np.array(a)
Numpy内生函数转化
x = np.arange(5)
print(x)
从硬盘中读取
delimiter=’,'用逗号隔开,skiprows=1跳过第一行 ,usecols=(1, 4, 6)选取1,4,6列,unpack=True 把四列数据分开
open, close, v = np.loadtxt('000001.csv', delimiter=',', skiprows=1, usecols=(1, 4, 6), unpack=True)
以2为步长选取数组
c = np.arange(11)
print(c[::2])
[ 0 2 4 6 8 10]
排序
用x.func() 进行排序,x有变换
如果用np.func(x) ,不对x本身造成影响
c = np.random.randint(1, 100, 10)
print(c)
y = np.sort(c)
print(y)
y = c.sort()
print(c)
二、散点图
散点图显示两组数据的值,每个点的坐标位置由变量的值决定
由一组不相关的点组成,观察两种变量之间的相关性
height = [161, 170, 182, 175, 173, 165]
weight = [50, 58, 80, 70, 69, 55]
plt.scatter(height, weight)
plt.show()
N = 1000
x = np.random.randn(N)
y = np.random.randn(N)
plt.scatter(x, y)
plt.show()
N = 1000
x = np.random.randn(N)
y = x+np.random.randn(N)*0.5
plt.scatter(x, y)
plt.show()
N = 1000
x = np.random.randn(N)
y = -x+np.random.randn(N)*0.5
plt.scatter(x, y)
plt.show()
实例:股票价格的涨幅
取 除去最后一天的所有数据, 取除去第一天的所有数据
open, close = np.loadtxt('000001.csv', delimiter=',', skiprows=1, usecols=(1, 4), unpack=True)
change = close - open
yesterday = change[:-1] #除开最后一个的所有元素
today = change[1:] #除开第一个的所有元素
plt.scatter(yesterday, today)
plt.show()
散点图的外观调整
颜色,c
点大小,s
透明度,alpha
点形状,marker
plt.scatter(yesterday, today, s=500, c='r', alpha=0.5)
折线图
是将直线段把各数据连接起来组成的图形
常用来观察数据随时间变换的趋势
例如股票价格,温度变化等
画出x平方
x = np.linspace(-10, 10, 100)
y = x**2
plt.plot(x, y)
plt.show()
date, open, close = np.loadtxt('000001.csv', delimiter=',',
converters={
0: mdates.bytespdate2num('%m/%d/%Y')},
skiprows=1, usecols=(0, 1, 4), unpack=True)
plt.plot(date, open)
plt.show()
plt.plot_date(date, open, '-')
plt.show()
更改参数
线型,linestyle
颜色, color
点形状,market
画出正弦图
x = np.linspace(0, 2*np.pi, 50) #0-2pi中显示50个点
y = np.sin(x)
plt.plot(x, y)
plt.show()
条形图
以长方形的长度为变量的统计图表
用来比较多个项目的分类的数据大小
通常利用较小的数据集分析
例如不同季度的销量,不同国家的人口等
N = 5
y = [20, 10, 30, 25, 15]
index = np.arange(N)
pl = plt.bar(x=index, height=y, color='red', width=0.5) #x是横坐标, y是高度
plt.show()
N = 5
y = [20, 10, 30, 25, 15]
index = np.arange(N)
pl = plt.barh(left=0, y=index, width=y) #x是横坐标, y是高度
plt.show()
index = np.arange(4)
sales_BJ = [52, 55, 63, 53]
sales_SH = [44, 66, 55, 41]
bar_width = 0.3
plt.bar(index, sales_BJ, bar_width, color='b')
plt.bar(index+bar_width, sales_SH, bar_width, color='r') #平移一个bar_width单位
index = np.arange(4)
sales_BJ = [52, 55, 63, 53]
sales_SH = [44, 66, 55, 41]
bar_width = 0.3
plt.bar(index, sales_BJ, bar_width, color='b')
plt.bar(index, sales_SH, bar_width, color='r', bottom=sales_BJ)