Python數(shù)據(jù)分析與展示Numpy、Matplotlib

Python 數(shù)據(jù)分析與展示

學(xué)習(xí)內(nèi)容

Numpy數(shù)據(jù)表示、Matplotlib繪圖、Pandas數(shù)據(jù)分析這三個(gè)庫(kù)

Anaconda IDE的使用

conda、Spyder、IPython的使用

實(shí)例:圖像的手繪風(fēng)格、引力波的繪制、房?jī)r(jià)趨勢(shì)分析、股市數(shù)據(jù)的分析


Anaconda IDE的使用

使用anaconda navigator 啟動(dòng)

anaconda來(lái)源于conda(用于管理python的第三方包與python環(huán)境)其包含了conda、Python與一批第三方的庫(kù)

編程工具 Spyder 包含了IPython(交互式命令行)
IPython中的?可以得到變量信息與函數(shù)信息、%run命令可以運(yùn)行python程序,在運(yùn)行時(shí)會(huì)使用空的命令空間、%magic可以顯示所有的魔術(shù)命令


image
![Uploading polar_331910.png . . .]
image ![Uploading polar_331910.png . . .]

數(shù)據(jù)的表示Numpy

數(shù)據(jù)的維度:一組數(shù)據(jù)的組織形式

Numpy 一個(gè)開(kāi)源的科學(xué)計(jì)算庫(kù),提供了一個(gè)強(qiáng)大的N維數(shù)組對(duì)象:ndarray,具有數(shù)學(xué)計(jì)算的功能

ndarray由實(shí)際的數(shù)據(jù)與描述數(shù)據(jù)的元數(shù)據(jù)兩部分組成,一般要求數(shù)據(jù)的類型相同。

生成ndarray:

  • np.array([[],[]],dtype=np.float32),也可以使用元組進(jìn)行創(chuàng)建
  • np.arrange(n) 類似range()函數(shù)
  • np.ones(shape)、np.zeros(shape)、np.full(shape,val)根據(jù)元組shape生成一個(gè)全1、全0、全val的ndarray數(shù)組
  • np.eye(n) 創(chuàng)建一個(gè)n維單位陣(以上均可以由dtype指定數(shù)據(jù)類型
  • np.ones_like(a)、np.zeros_like(a)、np.full_like(a,val) 由a給定形狀
  • np.linspace() 由起止數(shù)等間距地填充數(shù)據(jù),形成數(shù)組,類似于range,但是給定的參數(shù)為start、end、number
  • np.concatenate() 將兩個(gè)或多個(gè)數(shù)組合并成同一個(gè)數(shù)組

ndarray對(duì)象的屬性:

屬性 說(shuō)明
.ndim 維度的數(shù)量
.shape ndarray的尺度
.size 對(duì)象中元素的個(gè)數(shù)
.dtype 對(duì)象元素類型
.itemsize 每個(gè)元素的大小,以字節(jié)為單位

ndarray維度變換

  • .reshape(shape)不改變數(shù)組的元素,返回一個(gè)shape形狀的新的數(shù)組
  • resize(shape) 修改原數(shù)組
  • swapaxes(ax1,ax2) 將數(shù)組的n個(gè)維度中的兩個(gè)維度進(jìn)行調(diào)換
  • flatten() 降維 不改變?cè)瓟?shù)組

ndarray數(shù)組類型變換

new_a = a.astype(new_type)

ndarray轉(zhuǎn)為列表

list = a.tolist()

ndarray數(shù)組操作(索引與切片)

一維數(shù)組的索引與python類似,切片a[1:4:2] 起始編號(hào)、終止編號(hào)(不含)、步長(zhǎng)

多維數(shù)組的索引:a[1,2,3]從最外層到最內(nèi)層
多維數(shù)組的切片:a[:,1:3,:],a[:,:,::2]

ndarray數(shù)組的運(yùn)算

標(biāo)量運(yùn)算等價(jià)于對(duì)每一個(gè)元素進(jìn)行運(yùn)算

Numpy中的一元函數(shù)

  • np.abs(x)、np.fabs(x)、np.sqrt(x)、np.square(x)
  • np.log(x)、np.log10(x)
  • np.ceil(x)、np.floor(x)計(jì)算ceiling(不超過(guò)其的最大整數(shù)值)與floor(超過(guò)其最小整數(shù)值)
  • np.rint(x) 四舍五入值
  • np.modf(x) 以整數(shù)和小數(shù)兩個(gè)數(shù)組返回
  • np.cosh(x) ···
  • np.exp(x)、np.sign(x)
  • ···

Numpy中的二元函數(shù)

  • +-* / **
  • np.maximum(x,y)、np.minimum(x,y) 元素的最大、小值,生成新的數(shù)組
  • =、!=、>、<、<=、>= 比較大小返回布爾型數(shù)組

CSV文件(Comma-Separated Value,逗號(hào)分隔值)

文件單行以逗號(hào)進(jìn)行分隔,常見(jiàn)數(shù)據(jù)庫(kù)均可以讀入或到處CSV文件

np.savetxt(fname,array,fmt='%.18e',delimiter=None)
  • fname 文件名稱
  • array 要存入的數(shù)組
  • fmt 寫(xiě)入文件的格式,如%d %0.2
  • delimiter 分隔字符串,默認(rèn)為空格
np.loadtxt(fname,dtype=np.float,delimiter=None,unpack=False)
  • fname 文件名稱
  • dtype 數(shù)組元素格式
  • delimiter 分隔字符串,默認(rèn)為空格
  • unpack 默認(rèn)為False,讀入數(shù)據(jù)存入一個(gè)變量

多維數(shù)組的存取

a.tofile(fid, sep="", format="%s")
  • fid : 文件名或者是打開(kāi)的文件對(duì)象
  • sep : 數(shù)據(jù)分割字符串,空串則輸出二進(jìn)制文件
  • format : 輸出格式
np.fromfile(file, dtype=float, count=-1, sep='')
  • count : int
    Number of items to read. -1 means all items
np.save(file, array)/np.savez(file, array)
np.load(fname)
  • 存為.npy或者.npz文件

Numpy隨機(jī)函數(shù)子庫(kù)np.random庫(kù)

  • rand(d0,d1,...,dn)根據(jù)d0-dn創(chuàng)建隨機(jī)數(shù)組,浮點(diǎn)數(shù),[0,1),均勻分布
  • randn(d0,d1,...,dn) 正態(tài)分布
  • randint(low[,high,shape]) 隨機(jī)整數(shù)
  • seed(s) 隨機(jī)數(shù)種子
  • shuffle(a) 將第一軸進(jìn)行重排列,改變數(shù)組
  • permutation(a) 由第一軸產(chǎn)生一個(gè)新的亂序數(shù)組,不改變數(shù)組
  • choice(a[,size,replace,pl]) 從一位數(shù)組a中以概率p抽取元素,形成size形狀新數(shù)組,replace表示是否可以重用,默認(rèn)True
  • uniform()、normal、poisson

Numpy的統(tǒng)計(jì)函數(shù)

  • .sum(a,axis = None) 給定軸的求和或所有求和
  • .mean(a,axis = None) 算數(shù)平均數(shù)
  • .average(a,axis = None,weights = None) 加權(quán)平均數(shù)
  • .std(a,axis = None) 標(biāo)準(zhǔn)差
  • .var(a,axis = None) 方差
  • .min(a) max(a)
  • argmin(a) argmax(a) 一維后的最小、大值的下標(biāo)
  • unravel_index(index,shape) 根據(jù)shape將一維下標(biāo)index轉(zhuǎn)為多維下標(biāo)
  • ptp(a) 極差
  • median(a) 中位數(shù)
  • gradient(a) 計(jì)算數(shù)組的梯度 連續(xù)值之間的變化率

實(shí)例:圖像的手繪表示

圖像一般采用RGB表示,三個(gè)通道取值都在0-255

Python中的PIL庫(kù)(Python Image Library)

安裝 pip install pillow
使用 from PIL import Image

圖像在計(jì)算機(jī)中的表示為一個(gè)二元矩陣,每個(gè)矩陣元素為RGB值:(R,G,B) 每個(gè)通道為一個(gè)字節(jié),那么一個(gè)矩陣元素的大小就是3個(gè)字節(jié)(24二進(jìn)制位)

# 打開(kāi)圖像
im_array = np.array(Image.open('D:/test.jpg'))
# 保存到文件
im = Image.fromarray(im_array)
im.save(filename)

# 灰度變換
a = np.array(Image.open('D:/test.jpg').convert('L'))

手繪圖片:黑白灰色,邊界線條較重,相同或者相近的顏色趨向于白色,略有光源效果

# -*- coding: utf-8 -*-
"""
圖像手繪風(fēng)格實(shí)例代碼
"""


from PIL import Image
import numpy as np

a = np.array(Image.open('D:/leiding.jpg').convert('L')).astype('float')


depth = 10.
grad = np.gradient(a)
grad_x, grad_y = grad

grad_x = grad_x *depth/100.
grad_y = grad_y *depth/100.

A = np.sqrt(grad_x**2+grad_y**2+1.)

uni_x = grad_x/A
uni_y = grad_y/A

uni_z = 1./A

vec_e1 = np.pi/2.2
vec_az = np.pi/4

dx = np.cos(vec_e1)*np.cos(vec_az)
dy = np.cos(vec_e1)*np.sin(vec_az)
dz = np.sin(vec_e1)

b = 255*(dx*uni_x+dy*uni_y+dz*uni_z)
b = b.clip(0,255)

im = Image.fromarray(b.astype('uint8'))

im.save('D:/handpaint.jpg')

 

Matplotlib庫(kù)

使用方法:

import matplotlib.pyplot as plt
plt.plot([3,1,4,5,2])
plt.ylabel('grade')
plt.show()

# 存為文件

plt.savefig('test',dpi = 600) #默認(rèn)輸出為PNG 文件

plt運(yùn)行結(jié)果.png

同樣也可以這樣繪制:


plt.plot([0,2,4,6,8],[3,1,4,5,2])


# 給出橫縱坐標(biāo)的范圍 橫-1到10,縱0到6
plt.axis([-1,10,0,6])

# 繪圖區(qū)域分割
plt.subPlot(nrows,ncols,plot_number) # 與matlab一樣,標(biāo)號(hào)從左到右,從上到下

# 也可以將逗號(hào)去掉,比如plt.subplot(324)



plt.plot(x,y,format_string,**kwargs)

  • x: X軸數(shù)據(jù),列表或者數(shù)組,可選,可組合使用
  • y: Y軸數(shù)據(jù),列表或者數(shù)組
  • format_stirng: 控制輸出字符串,可選
    • 'b'/'g'/'#008000'/'0.8' 顏色控制字符
    • '-' 實(shí)線 '--' 破折線 '-.' 點(diǎn)劃線 ':' 虛線 '''' 無(wú)線條 曲線風(fēng)格字符
    • '.' 點(diǎn)標(biāo)記 ',' 像素標(biāo)記 'o' 實(shí)心圈標(biāo)記 'v' 倒三角標(biāo)記 '^' 上三角標(biāo)記 ...... 標(biāo)記字符
  • **kwargs: 第二組或者更多組的(x,y,format_string)

plt中的文本顯示函數(shù)

  • plt.xlabel()、plt.ylabel() 對(duì)軸加上標(biāo)簽
  • plt.title() 增加文件頭
  • plt.text() 任意位置增加文本
    • plt.text(2,1,'str') 前兩個(gè)參數(shù)表示text出現(xiàn)范圍
  • plt.annotate() 增加帶箭頭的注釋文本
  • plt.grid() 顯示網(wǎng)格線

plt.subplot2grid(GridSpec,CurSpec,colspan=1,rowspan=1)

設(shè)定網(wǎng)格,選中網(wǎng)格,設(shè)計(jì)成不同大小的繪圖子區(qū)域

  • GridSpec 元組,表示將區(qū)域分成什么樣子的子區(qū)域
  • CurSpec 元組,表示子區(qū)域的起始格子坐標(biāo)
  • colspan、rowspan 表示子區(qū)域占用列、行數(shù)
    同樣,此函數(shù)可以使用如下庫(kù)實(shí)現(xiàn):
import matplotlib.gridspec as grs

gs  = grs.GridSpec(3,3)
ax1 = plt.subplot(gs[0:])
ax2 = plt.subplot(gs[1,:-1])

pyplot基礎(chǔ)圖標(biāo)函數(shù)

plot()函數(shù)、箱形圖函數(shù)boxplot()、條形圖函數(shù)bar()、橫向條形圖函數(shù)barh()、極坐標(biāo)圖函數(shù)polar()、餅圖pie()
功率譜密度圖函數(shù)psd()、譜圖specgram()、X-Y相關(guān)性圖cohere()、散點(diǎn)圖scatter()、直方圖hist()、步階圖step()、等值圖contour()、垂直圖vlines()、柴火圖stem()、數(shù)據(jù)日期plot_date()

下面以代碼說(shuō)明:

# -*- coding: utf-8 -*-
"""
Created on Tue Aug  1 14:07:25 2017

@author: Administrator
"""

import matplotlib.pyplot as plt


# 餅圖的標(biāo)簽
labels = 'Frogs','Hogs','Dogs','Logs'

# 餅圖對(duì)應(yīng)的尺寸,即所占比例
sizes = [15,30,45,10]

# 突出與突出的量
explode = (0,0.1,0,0)

# autopct顯示百分?jǐn)?shù)的方式、shadow陰影效果、startangele起始角度

plt.pie(sizes,explode=explode,labels=labels,autopct = '%1.1f%%',shadow = False,startangle = 90)


# 使得軸的度量成為一樣
plt.axis('equal')
plt.show()
pie.png
# -*- coding: utf-8 -*-
"""
Created on Tue Aug  1 15:39:08 2017

@author: Administrator
"""
# 繪制直方圖

import matplotlib.pyplot as plt
import numpy as np

np.random.seed(0)
mu,sigma = 100,20 #均值與標(biāo)準(zhǔn)差

a = np.random.normal(mu,sigma,size=100) # 正態(tài)分布


# a 給定數(shù)組 bin 表示直方的個(gè)數(shù),就是取值區(qū)間的劃分,縱軸表示為頻次/區(qū)間長(zhǎng)度
# normed = 0 顯示頻次,normed=1 顯示頻次/區(qū)間長(zhǎng)度
# histtype 繪制類型 facecolor 繪制顏色

plt.hist(a,20,normed = 1,histtype = 'stepfilled',facecolor = 'b',alpha = 0.75)

plt.title('Histgram')

plt.savefig('D:/Histgram',dpi = 150)

plt.show()

Histgram.png
# -*- coding: utf-8 -*-
"""
Created on Tue Aug  1 15:48:07 2017

@author: Administrator
"""

# 極坐標(biāo)圖的繪制
import matplotlib.pyplot as plt
import numpy as np

# 極坐標(biāo)圖中的數(shù)據(jù)個(gè)數(shù)
N = 20

# 等分出20個(gè)不同的角度 0-360度
theta = np.linspace(0.0,2*np.pi,N,endpoint = False)

# 生成每個(gè)角度對(duì)應(yīng)的值
radii = 10*np.random.rand(N)

# 生成寬度值
width = np.pi/4*np.random.rand(N)


# 獲得繪制極坐標(biāo)圖的子區(qū)域
ax = plt.subplot(111,projection = 'polar')

# 前三個(gè)參數(shù)對(duì)應(yīng) theta 從何地開(kāi)始繪制 radii 從中心點(diǎn)繪制出來(lái)的長(zhǎng)度,width 指繪圖區(qū)域的面積
bars = ax.bar(theta,radii,width=width,bottom=0.0)

for r,bar in zip(radii,bars):
    bar.set_facecolor(plt.cm.viridis(r/10.))
    bar.set_alpha(0.5)


plt.savefig('D:/polar',dpi = 150)

plt.show()
polar.png
# -*- coding: utf-8 -*-
"""
Created on Tue Aug  1 16:02:32 2017

@author: Administrator
"""

import numpy as np 
import matplotlib.pyplot as plt

fig,ax = plt.subplots()

ax.plot(10*np.random.randn(100),10*np.random.randn(100),'o')
ax.set_title('Simple Scatter')

plt.savefig('D:/Scatter',dpi = 150)

plt.show()
Scatter.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容