以下为学习科学计算模块时的一些代码(回顾学习时参考):
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 30 13:32:27 2017
@author: Administrator
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#定义资料集
df1 = pd.DataFrame(np.ones((3,4))*0,columns=['a','b','c','d'])
df2 = pd.DataFrame(np.ones((3,4))*1,columns=['a','b','c','d'])
df3 = pd.DataFrame(np.ones((3,4))*2,columns=['a','b','c','d'])
#contact纵向合并
res1 = pd.concat([df1,df2,df3],axis=0)
print(res1)
#======================================================
df4 = pd.DataFrame(np.ones((3,4))*0,columns=['a','b','c','d'],index=[1,2,3])
df5 = pd.DataFrame(np.ones((3,4))*1,columns=['b','c','d','e'],index=[2,3,4])
#join,['inner','outer'] 默认为outer
#res = pd.concat([df1,df2])
res2 = pd.concat([df4,df5],join='inner',ignore_index=True)
print(res2)
#======================================================
df1 = pd.DataFrame(np.ones((3,4))*0,columns=['a','b','c','d'],index=[1,2,3])
df2 = pd.DataFrame(np.ones((3,4))*1,columns=['a','b','c','d'])
df3 = pd.DataFrame(np.ones((3,4))*1,columns=['b','c','d','e'],index=[2,3,4])
res = df1.append(df2,ignore_index=True)
res = df1.append([df2,df3])
s1 =pd.Series([1,2,3,4],index=['a','b','c','d'])
#res = df1.append(s1,ignore_index=True)
print(res)
#======================================================
A = np.array([1,1,1])
B = np.array([2,2,2])
C = np.vstack((A,B)) #Vertical stack 上下合并
D = np.hstack((A,B)) #horziontal stack 左右合并(序列)
print(D)
print(A.shape,D.shape)
print(A.T.shape)
print(A[np.newaxis,:].shape) #在行上加了一个维度
print(A[:,np.newaxis].shape) #在纵向加了维度
A = np.array([1,1,1])[:,np.newaxis]
B = np.array([2,2,2])[:,np.newaxis]
print(np.vstack((A,B)))
print(np.hstack((A,B)))
C = np.concatenate((A,B,B,A),axis=1)
print(C)
#======================================================
A = np.arange(12).reshape((3,4))
print(A)
B = np.split(A,3,axis=0)
print(B)
print(np.vsplit(A,3))
print(np.hsplit(A,2))
#======================================================
left = pd.DataFrame({'key1':['K0','K0','K1','K2'],
'key2':['K0','K1','K0','K1'],
'A':['A0','A1','A2','A3'],
'B':['B0','B1','B2','B3']})
right = pd.DataFrame({'key1':['K0','K1','K1','K2'],
'key2':['K0','K0','K0','K0'],
'C':['C0','C1','C2','C3'],
'D':['D0','D1','D2','D3']})
print(left)
print(right)
res = pd.merge(left,right,on=['key1','key2'],how='outer')
print(res)
#======================================================
df1 = pd.DataFrame({'coll':[0,1],
'col_left':['a','b']})
df2 = pd.DataFrame({'coll':[1,2,2],
'col_right':[2,2,2]})
print(df1)
print(df2)
#res = pd.merge(df1,df2,on='coll',how='outer',indicator=True)
res = pd.merge(df1,df2,on='coll',how='outer',indicator='indicator_column')
print(res)
#======================================================
#plot data
#Series
data = pd.Series(np.random.randn(1000),index=np.arange(1000))
data = data.cumsum()
#DataFrame
data = pd.DataFrame(np.random.randn(1000,4),index=np.arange(1000),columns=list('ABCD'))
data = data.cumsum()
print(data.head())
#plot methods:
#'bar','hist','box','kde','area','hexbin','pie'
#data.plot()
ax = data.plot.scatter(x='A',y='B',color='Red',label='Class 1')
data.plot.scatter(x='A',y='C',color='DarkGreen',label='Class 2',ax=ax)
plt.show()
#matplotlib
x = np.linspace(-3,3,50)
y1 = 2*x + 1
y2 = x**2
plt.figure()
plt.plot(x,y1)
plt.figure(3,figsize=(4,3))
plt.plot(x,y2)
plt.plot(x,y1,color='red',linewidth=5.0,linestyle='--')
plt.show()
#======================================================
x = np.linspace(-3,3,50)
y1 = 2*x + 1
y2 = x**2
plt.figure(3,figsize=(4,3))
l1, = plt.plot(x,y2,label='up')
l2, = plt.plot(x,y1,color='red',linewidth=1.0,linestyle='--',label='down')
plt.xlim((-1,2))
plt.ylim((-2,3))
plt.xlabel('I am x')
plt.ylabel('I am y')
plt.legend(handles=[l1,l2],labels=['aaa','bbb'],loc='best')
new_ticks = np.linspace(-1,2,5)
#print(new_ticks)
plt.xticks(new_ticks)
plt.yticks([-2,-1.8,-1,1.22,3],
[r'$really\ bad$',r'$bad$',r'$normal$',r'$good$',r'$really\ good$'])
#gca = 'get current axis'
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.spines['bottom'].set_position(('data',0)) # outward,axes
ax.spines['left'].set_position(('data',0))
x0 = 1
y0 = 2*x0 + 1
plt.scatter(x0,y0,s=50,color='b')
plt.plot([x0,x0],[y0,0],'k--',lw=2.5)
#method 1
plt.annotate(r'$2x+1=%s$'%y0,xy=(x0,y0),xycoords='data',xytext=(+30,-30),textcoords='offset points',fontsize=16,arrowprops=dict(arrowstyle='->',connectionstyle='arc3,rad=.2'))
#method 2
plt.text(-3.7,3,r'$This\ is\ the\ some\ text$',fontdict={'size':16,'color':'r'})
plt.show()
#======================================================
x = np.linspace(-3,3,50)
y = 0.5*x + 1
plt.figure()
plt.plot(x,y,linewidth=10)
plt.ylim((-2,2))
#gca = 'get current axis'
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.spines['bottom'].set_position(('data',0)) # outward,axes
ax.spines['left'].set_position(('data',0))
for label in ax.get_xticklabels() + ax.get_yticklabels():
label.set_fontsize(12)
label.set_bbox(dict(facecolor='white',edgecolor='None',alpha=0.7))
plt.show()
#======================================================
n = 1024
X = np.random.normal(0,1,n)
Y = np.random.normal(0,1,n)
T = np.arctan2(Y,X)
#plt.scatter(X,Y,s=75,c=T,alpha=0.5)
plt.scatter(np.arange(5),np.arange(5))
#plt.xlim((-1.5,1.5))
#plt.ylim((-1.5,1.5))
plt.xticks(())
plt.yticks(())
plt.show()
#======================================================
n = 12
X = np.arange(n)
Y1 = (1-X/float(n))*np.random.uniform(0.5,1.0,n)
Y2 = (1-X/float(n))*np.random.uniform(0.5,1.0,n)
plt.bar(X,+Y1,facecolor='#9999ff',edgecolor='white')
plt.bar(X,-Y2,facecolor='#ff9999',edgecolor='white')
for x,y in zip(X,Y1):
#ha:hoeizontal alignment
plt.text(x+0.4,y+0.05,'%.2f'%y,ha='center',va='bottom')
for x,y in zip(X,Y2):
#ha:hoeizontal alignment
plt.text(x+0.4,-y-0.05,'-%.2f'%y,ha='center',va='top')
plt.xlim((-.5,n))
plt.ylim((-1.5,1.5))
plt.xticks(())
plt.yticks(())
plt.show()
#======================================================
def f(x,y):
return (1 - x/2 + x**5 + y**3) * np.exp(-x**2 - y**2)
n = 256
x = np.linspace(-3,3,n)
y = np.linspace(-3,3,n)
X,Y = np.meshgrid(x,y)
plt.contourf(X,Y,f(X,Y),8,alpha=0.75,cmap=plt.cm.hot)
C = plt.contour(X,Y,f(X,Y),8,colors='black',linewidth=.5)
plt.clabel(C,inline=True,fontsize=10)
plt.xticks(())
plt.yticks(())
plt.show()
#======================================================
a = np.array([0.313660827978, 0.365348418405, 0.423733120134,
0.365348418405, 0.439599930621, 0.525083754405,
0.423733120134, 0.525083754405, 0.651536351379]).reshape(3,3)
plt.imshow(a,interpolation='nearest',cmap='bone',origin='upper')
plt.colorbar(shrink=.92)
plt.xticks(())
plt.yticks(())
plt.show()
#======================================================
fig = plt.figure()
ax = Axes3D(fig)
x = np.arange(-4,4,0.25)
y = np.arange(-4,4,0.25)
X,Y = np.meshgrid(x,y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
ax.plot_surface(X,Y,Z,rstride=1,cstride=1,cmap=plt.get_cmap('rainbow'))
ax.contourf(X,Y,Z,zdir='z',offset=-2,cmap='rainbow')
ax.set_zlim(-2,2)
plt.show()
#======================================================
plt.figure()
plt.subplot(2,1,1)
plt.plot([0,1],[0,1])
plt.subplot(2,3,4)
plt.plot([0,1],[0,2])
plt.subplot(235)
plt.plot([0,1],[0,3])
plt.subplot(236)
plt.plot([0,1],[0,4])
plt.show()
#======================================================
import numpy as np
plt.figure()
ax1 = plt.subplot2grid((3,3),(0,0),colspan=3,rowspan=1)
ax1.plot([1,2],[1,2])
ax1.set_title('ax1_title')
ax2 = plt.subplot2grid((3,3),(1,0),colspan=2,rowspan=1)
ax2.plot(np.sin(np.arange(0,2*np.pi,0.01)))
ax3 = plt.subplot2grid((3,3),(1,2),colspan=2,rowspan=1)
ax4 = plt.subplot2grid((3,3),(2,0))
ax5 = plt.subplot2grid((3,3),(2,1))
ax6 = plt.subplot2grid((3,3),(2,2))
plt.tight_layout()
plt.show()
#======================================================
import matplotlib.gridspec as gridspec
plt.figure()
gs = gridspec.GridSpec(3,3)
ax1 = plt.subplot(gs[0,:])
ax2 = plt.subplot(gs[1,:2])
ax3 = plt.subplot(gs[1,-1])
ax4 = plt.subplot(gs[2,0])
ax5 = plt.subplot(gs[2,1])
ax6 = plt.subplot(gs[2,2])
plt.tight_layout()
plt.show()
#======================================================
f,((ax11,ax12),(ax21,ax22)) = plt.subplots(2,2,sharex=True,sharey=True)
ax11.scatter([1,2],[1,2])
plt.tight_layout()
plt.show()
#======================================================
from matplotlib import pyplot as plt
fig = plt.figure()
x = [1,2,3,4,5,6,7]
y = [1,3,4,2,5,8,6]
left, bottom, width, height = 0.1, 0.1, 0.8, 0.8
ax1 = fig.add_axes([left, bottom, width, height])
ax1.plot(x, y, 'r')
ax1.set_xlabel('x')
ax1.set_ylabel('y')
ax1.set_title('title')
left, bottom, width, height = 0.2, 0.6, 0.25, 0.25
ax2 = fig.add_axes([left, bottom, width, height])
ax2.plot(y, x, 'b')
ax2.set_xlabel('x')
ax2.set_ylabel('y')
ax2.set_title('title inside 1')
plt.axes([0.6, 0.2, 0.25, 0.25])
plt.plot(y[::-1], x, 'g') # 注意对y进行了逆序处理
plt.xlabel('x')
plt.ylabel('y')
plt.title('title inside 2')
plt.show()
#======================================================
x = np.arange(0,10,0.1)
y1 = 0.05*x**2
y2 = -1*y1
fig,ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(x, y1, 'g-') # green, solid line
ax1.set_xlabel('X data')
ax1.set_ylabel('Y1 data', color='y')
ax2.plot(x, y2, 'b-') # blue
ax2.set_ylabel('Y2 data', color='r')
plt.show()