mooc網(wǎng)python數(shù)據(jù)分析與展示
1.conda,spyder,ipython
2.對于創(chuàng)建后的ndarray數(shù)組,可以對其進行維度變換和元素類型變換。
a=np.ones((2,3,4),dtype=np.int32)
3.reshape(shape)不改變數(shù)組元素,返回一個shape形狀的數(shù)組,原數(shù)組不變
.resize(shape)與reshape功能一致,但修改原數(shù)組
.swapaxes(ax1,ax2)對數(shù)組n個維度中兩個維度進行調(diào)換
.flatten(),降維,不改變原數(shù)組.
4.new_a=a.astype(new_type)
astype會創(chuàng)建新數(shù)組
5.ls=a.tolist()數(shù)組向列表的轉(zhuǎn)換。
6.np.rint(x)計算數(shù)組各元素的四舍五入值
np.modf(x)將數(shù)組各元素的小數(shù)和整數(shù)部分分別返回
np.sign(x)計算數(shù)組各元素的符號值
np.tanh(x)雙曲型三角函數(shù)。
np.copysigh(x,y)將數(shù)組y中各個元素值的符號賦值給數(shù)組x對應(yīng)元素。
np.savetxt(frame,array,fmt='%.18e',delimiter=None)
np.loadtxt(frame,dtype=np.float,delimiter=None,unpack=False)
csv只能存取一維和二維數(shù)組。
7.a.tofile(frame,sep='',format='%s')
frame:文件,字符串.
sep:數(shù)據(jù)分割字符串,空串寫入文件為二進制
format:寫入數(shù)據(jù)的格式
np.fromfile(frame,dtype=float,count=-1,sep='')
count-1是讀入整個文件
8.np.save(fname,array) 擴展名為.NPY
np.savez(fname,array) 擴展名為.npz
np.load(fname)
與其他程序進行交流的話不適合用這種方式
9.numpy庫的隨機函數(shù)
np.random.randint(100,200,(3,4))
shuffle(a)根據(jù)數(shù)組a的第1軸進行隨機排列,改變數(shù)組x
permutation(a)不改變數(shù)組x
choice(a[,size,replace,p])從一維數(shù)組a中以概率p抽取元素,形成size形狀新數(shù)組replace表示是否可以重用元素,默認為false
np.random.choice(b,(3,2),replace=False)
np.random.choice(b,(3,2),p=b/np.sum(b))
10.uniform(low,high,size)均勻分布,起始結(jié)束
normal(loc,scale,size)正態(tài)分布,均值,標準差
poisson(lam,size)泊松分布 隨機率
11.sum(a,axis=None)
mean(a,axis=None)
average(a,axis=None,weight=None)期望 權(quán)重
std(a,axis=None)標準差
var(a,axis=None)方差
12.min(a),max(a),argmin(a),argmax(a),unravel_index(index,shape)根據(jù)shape將一維下標index轉(zhuǎn)換成多維下標,ptp(a)計算數(shù)組a中元素最大值與最小值的差,median(a)計算數(shù)組a元素的中位數(shù)。
13.np.gradient(f)計算數(shù)組f中元素的梯度,當(dāng)f為多維時,返回每個維度梯度。
14.一二維數(shù)據(jù)可以用csv文件,np.loadtxt(),np.savetxt()
多維數(shù)據(jù)存取,a.tofile(),np.fromfilr(),np.save(),np.savez(),np.load().
15.np.random.rand(),np.random.randn(),np.random.randint(),np.random.seed(),np.random.shuffle(),np.random.permutation(),np.random.choice()
Matplotlib庫入門
1.pyplot繪圖區(qū)域
plt.subplot(nrows,ncols,plot_number).
2.plt.plot(x,y,format_string,kwargs)
format_string:控制曲線的格式字符串,多選
kwargs:可以下一條曲線
3.format_string 顏色,標記,風(fēng)格
c 青綠色 m 洋紅色
'.'點標記,','像素標記極小點,'o'實心圈,'v'倒三角,'^','>'右三角,'<','1'下花三角,'2'上花三角,'3'左花,'4'右花,'s'實心方形,'p'實心五角,'','h'豎六邊形,'H'橫六邊形,'+'十字標記,'x'x標記,'D'菱形標記,'d'瘦菱形,'|'垂直線。
'-','--','-.',':',''
plt.plot(a,a1.5,'go-')
4.plt.plot(x,y,format_string,kwargs)
format_string:color linestyle,marker,markerfacecolor,markersize
5.pyplot的中文顯示
import matplotlib.pyplot as plt
import matplotlib
matplotlib.rcParams['font.family']='SimHei'
plt.plot([3,1,4,5,2])
plt.ylabel("縱軸(值)")
plt.savefig('test',dpi=600)
plt.show()
6.font.family,font.style,font.size。
7.rcParams['font.family']
SimHei 中文黑體,Kaiti中文楷體,LiSu中文隸書,F(xiàn)angSong仿宋,YouYuan,STSong華文宋體
8.pyplot的中文顯示:第二種方法,在有中文輸出的地方,增加一個屬性:fontproperties。
9.pyplot的文本顯示:plt.xlable(),plt.ylable(),plt.title()整體增加文本標簽plt.text()對任意位置增加文本,plt.annotate()在圖形中增加帶箭頭的注解.
import numpy as np
import matplotlib.pyplot as plt
a=np.arange(0.0,5.0,0.02)
plt.plot(a,np.cos(2*np.pi*a),'r--')
plt.xlabel('橫軸:時間',fontproperties='SimHei',fontsize=15,color='green')
plt.ylabel('縱軸:振幅',fontproperties='SimHei',fontsize=15)
plt.title(r'正弦波實例$y=cos(2\pi x)$',fontproperties='SimHei',fontsize=25)
plt.text(2,1,r'$\mu=100$',fontsize=15)
plt.axis([-1,6,-2, 2])
plt.grid(True)
plt.show()
10.plt.annotate(s,xy=arrow_crd,xytext=text_crd,arrowprops=dict)
增加注釋,xy對應(yīng)箭頭所在位置,xytext文本顯示的位置,arrowprops字典類型對應(yīng)箭頭屬性、
plt.annotate(r'$\mu-100$',xy=(2,1),xytext=(3,1.5),arrowprops=dict(facecolor='black',shrink=0.1,width=2))
11.plt子繪制區(qū)域的設(shè)置
plt.subplot2grid()
plt.subplot2grid(GridSpec,CurSpec,colspan=1,rowspan=1)理念:設(shè)定網(wǎng)絡(luò),選中網(wǎng)絡(luò),確定選中行列區(qū)域數(shù)量,編號從0開始。設(shè)定幾行幾列,從幾行幾列開始,在列/行的方向上延伸
plt.subplot2grid((3,3),(1,0),colspan=2)。由上到下012由左到右012。
或者用GridSpec類
import matplotlib.gridspec as gridspec
gs=gridspec.GridSpec(3,3)
ax1=plt.subplot(gs[0,:])
ax2=plt.subplot(gs[1,:-1])
ax3=plt.subplot(gs[1:,-1])
ax4=plt.subplot(gs[2,0])
matplotlib基礎(chǔ)繪圖函數(shù)示例
1.plt.plot(x,y,fmt) 坐標圖
plt.boxplot(data,notch,position)箱型圖
plt.bar(left,height,width,bottom)條形圖
plt.barh(width,bottom,left,height)橫向條形
plt.polar(theta,r)極坐標圖
plt.pie(data,explode)餅圖
plt.psd(x,NFFT=256,pad_to,Fs)繪制功率譜密度圖
plt.specgram(x,NFFT=256,pad_to,F)譜圖
plt.cohere(x,y,NFFT=256,Fs)x-y相關(guān)性
plt.scatter(x,y)散點
plt.step(x,y,where)步階圖
plt.hist(x,bins,normed)直方圖
plt.contour(X,Y,Z,N)繪制等值圖
plt.vlines()繪制垂直圖
plt.stem(x,y,linefmt,markerfmt)繪制柴火圖
plt.plot_date()繪制數(shù)據(jù)日期
餅圖
import matplotlib.pyplot as plt
labels='Frogs','Hogs','Dogs','Logs'
sizes=[15,30,45,10]
explode=(0,0.1,0,0)
plt.pie(sizes,explode=explode,labels=labels,autopct='%1.1f%%',shadow=False,startangle=90
)
plt.axis('equal')
plt.show()
直方圖
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(0)
mu,sigma=100,20 #均值和標準差
a=np.random.normal(mu,sigma,size=100)
plt.hist(a,20,normed=1,histtype='stepfilled',facecolor='b',alpha=0.75)
plt.title('Histogram')
plt.show()
normed=0是個數(shù),normed=1是概率
極坐標
import numpy as np
import matplotlib.pyplot as plt
N=20
theta=np.linspace(0.0,2*np.pi,N,endpoint=False)
radii=10*np.random.rand(N)
width=np.pi/4*np.random.rand(N)
ax=plt.subplot(111,projection='polar')
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.show()
散點圖
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.show()
引力波
import numpy as np
import matplotlib.pyplot as plt
from scipy.io import wavfile
rate_h, hstrain= wavfile.read(r"H1_Strain.wav","rb")
rate_l, lstrain= wavfile.read(r"L1_Strain.wav","rb")
#reftime, ref_H1 = np.genfromtxt('GW150914_4_NR_waveform_template.txt').transpose()
reftime, ref_H1 = np.genfromtxt('wf_template.txt').transpose() #使用python123.io下載文件
htime_interval = 1/rate_h
ltime_interval = 1/rate_l
fig = plt.figure(figsize=(12, 6))
# 丟失信號起始點
htime_len = hstrain.shape[0]/rate_h
htime = np.arange(-htime_len/2, htime_len/2 , htime_interval)
plth = fig.add_subplot(221)
plth.plot(htime, hstrain, 'y')
plth.set_xlabel('Time (seconds)')
plth.set_ylabel('H1 Strain')
plth.set_title('H1 Strain')
ltime_len = lstrain.shape[0]/rate_l
ltime = np.arange(-ltime_len/2, ltime_len/2 , ltime_interval)
pltl = fig.add_subplot(222)
pltl.plot(ltime, lstrain, 'g')
pltl.set_xlabel('Time (seconds)')
pltl.set_ylabel('L1 Strain')
pltl.set_title('L1 Strain')
pltref = fig.add_subplot(212)
pltref.plot(reftime, ref_H1)
pltref.set_xlabel('Time (seconds)')
pltref.set_ylabel('Template Strain')
pltref.set_title('Template')
fig.tight_layout()
plt.savefig("Gravitational_Waves_Original.png")
plt.show()
plt.close(fig)
pandas庫入門
1.Series,DataFrame一維和二維
2.基本操作,運算操作,特征類操作,關(guān)聯(lián)類操作。
3.numpy是基礎(chǔ)數(shù)據(jù)類型,關(guān)注數(shù)據(jù)的結(jié)構(gòu)表達,維度是數(shù)據(jù)間的關(guān)系。
pandas是擴展數(shù)據(jù)類型,關(guān)注數(shù)據(jù)的應(yīng)用表達,維度是數(shù)據(jù)與索引間的關(guān)系。
4.pandas庫中的series類型
series由數(shù)據(jù)及與之對應(yīng)的相關(guān)數(shù)據(jù)索引組成
5.series由python列表,標量值,python字典,ndarray,其他函數(shù)創(chuàng)建。
import pandas as pd
標量:
s=pd.Series(25,index=['a','b','c'])
字典:
d=pd.Series({'a':9,'b':8})
想要鍵和值不一一對應(yīng):
e=pd.Series({'a':9,'b':8,'c':7}),index=['c','a','b','d'])
ndarray:
n=pd.Series(np.arange(5))
m=pd.Series(np.arange())
6.series操作
b.index獲得索引,b.values 獲得數(shù)據(jù)
series自動索引和自定義索引并存,但不能混用。
7.b[3]獲得是值
b[:3]獲得是索引加值。
8.只有當(dāng)選擇series中一個的時候,是一個值,其他的都是series類型
9.in只會判斷自定義索引
10.b.get('f',100)如果存在f,返回f,不存在,返回100.
11.a+b索引相同的值相加。
12.b.name,b.index.name。
13.pandas庫的dataframe類型
dataframe由共同相同索引的一組列組成