當前位置:首頁 » 編程語言 » pythonannotate

pythonannotate

發布時間: 2022-07-02 03:27:22

python panda怎麼提取列數據

創建數據

通過Python的zip構造出一元組組成的列表作為DataFrame的輸入數據rec。

In [3]: import pandas as pd
In [4]: import random
In [5]: num = random.sample(xrange(10000, 1000000), 5)
In [6]: num
Out[6]: [244937, 132008, 278446, 613409, 799201]
In [8]: names = "hello the cruel world en".split()
In [9]: names
Out[9]: ['hello', 'the', 'cruel', 'world', 'en']
In [10]: rec = zip(names, num)
In [15]: data = pd.DataFrame(rec, columns = [u"姓名",u"業績" ])
In [16]: data
Out[16]:
姓名 業績
0 hello 244937
1 the 132008
2 cruel 278446
3 world 613409
4 en 799201

DataFrame方法函數的第一個參數是數據源,第二個參數columns是輸出數據表的表頭,或者說是表格的欄位名。

導出數據csv

Windows平台上的編碼問題,我們可以先做個簡單處理,是ipython-notebook支持utf8.
import sys
reload(sys)
sys.setdefaultencoding("utf8")

接下來可以數據導出了。
In [31]: data
Out[31]:
姓名 業績
0 hello 244937
1 the 132008
2 cruel 278446
3 world 613409
4 en 799201
#在ipython-note里後加問號可查幫助,q退出幫助
In [32]: data.to_csv?
In [33]: data.to_csv("c:\\out.csv", index = True, header = [u"雇員", u"銷售業績"])

將data導出到out.csv文件里,index參數是指是否有主索引,header如果不指定則是以data里columns為頭,如果指定則是以後邊列表裡的字元串為表頭,但要注意的是header後的字元串列表的個數要和data里的columns欄位個數相同。

可到c盤用Notepad++打開out.csv看看。

簡單的數據分析
In [43]: data
Out[43]:
姓名 業績
0 hello 244937
1 the 132008
2 cruel 278446
3 world 613409
4 en 799201
#排序並取前三名
In [46]: Sorted = data.sort([u"業績"], ascending=False)
Sorted.head(3)
Out[46]:
姓名 業績
4 en 799201
3 world 613409
2 cruel 278446

圖形輸出
In [71]: import matplotlib.pyplot as plt
#使ipython-notebook支持matplotlib繪圖
%matplotlib inline
In [74]: df = data
#繪圖
df[u"業績"].plot()
MaxValue = df[u"業績"].max()
MaxName = df[u"姓名"][df[u"業績"] == df[u"業績"].max()].values
Text = str(MaxValue) + " - " + MaxName
#給圖添加文本標注
plt.annotate(Text, xy=(1, MaxValue), xytext=(8, 0), xycoords=('axes fraction', 'data'), textcoords='offset points')

如果注釋掉plt.annotate這行

Ⅱ 求Python這段代碼為什麼出錯

代碼沒有問題,但你涉及操作excel需要安裝xlrd
pip install xlrd
然後import這個xlrd

Ⅲ 在python 中打開波形文件 ︰ 未知的格式 ︰ 49.究竟怎麼了

投票
2
回答
1K
查看
我嘗試打開波形文件與 wave模塊,但是老是同樣的錯誤我試著不管。 包含錯誤的行是以下 ︰
wav = wave.open(f)

這是錯誤消息 ︰
Traceback (most recent call last):
File "annotate.py", line 47, in <mole>
play(file)
File "annotate.py", line 33, in play
wav = wave.open(f)
File "C:\Program Files (x86)\Python\lib\wave.py", line 498, in open
return Wave_read(f)
File "C:\Program Files (x86)\Python\lib\wave.py", line 163, in __init__
self.initfp(f)
File "C:\Program Files (x86)\Python\lib\wave.py", line 143, in initfp
self._read_fmt_chunk(chunk)
File "C:\Program Files (x86)\Python\lib\wave.py", line 269, in _read_fmt_chunk
raise Error('unknown format: %r' % (wFormatTag,))
wave.Error: unknown format: 49

字元串 f是路徑。WAV 文件,它工作在任何我的媒體播放器播放時。 我當然導入 wave的模塊。 我試過 f,作為一個相對和絕對路徑。 我試著用"wav"取代"WAV"。
錯誤什麼導致的?
投票
Python 的波模塊工作與特定類型的 WAV: PCM (WAVE_FORMAT_PCM: 0x0001)。
在您的情況下,您使用 WAV 類型 WAVE_FORMAT_GSM610[0x0031 = hex(49)].
你可以使用像大膽或者一些程序轉換的編解碼器,WAV 文件的類型更改為 lib。

Ⅳ python matplotlib 怎麼多邊形形

python matplotlib 怎麼多邊形形
y軸默認會有數值,你是需要自定義嗎
可以使用yticks函數,第一個參數是y軸的位置,第二個參數是具體標簽

import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0,6)
y = x * x
plt.plot(x, y, marker='o')
plt.yticks(y, ['a','b','c','d','e','f'])
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0,6)
y = x * x

plt.plot(x, y, marker='o')
for xy in zip(x,y):
plt.annotate("(%s,%s)" % xy, xy=xy, xytext=(-20,10), textcoords = 'offset points')

Ⅳ python是否有繪制混淆矩陣的函數,怎麼來實現

#-*-coding:UTF-8-*-
"""繪制混淆矩陣圖"""
importmatplotlib.pyplotasplt
fromsklearn.metricsimportconfusion_matrix


defconfusion_matrix_plot_matplotlib(y_truth,y_predict,cmap=plt.cm.Blues):
"""Matplotlib繪制混淆矩陣圖
parameters
----------
y_truth:真實的y的值,1darray
y_predict:預測的y的值,1darray
cmap:畫混淆矩陣圖的配色風格,使用cm.Blues,更多風格請參考官網
"""
cm=confusion_matrix(y_truth,y_predict)
plt.matshow(cm,cmap=cmap)#混淆矩陣圖
plt.colorbar()#顏色標簽

forxinrange(len(cm)):#數據標簽
foryinrange(len(cm)):
plt.annotate(cm[x,y],xy=(x,y),horizontalalignment='center',verticalalignment='center')

plt.ylabel('Truelabel')#坐標軸標簽
plt.xlabel('Predictedlabel')#坐標軸標簽
plt.show()#顯示作圖結果


if__name__=='__main__':
y_truth=[1,0,1,1,1,1,1,1,1,1,0,0,0,0,0]
y_predict=[1,0,0,1,0,1,1,1,1,1,0,1,0,1,0]
confusion_matrix_plot_matplotlib(y_truth,y_predict)

Ⅵ python的Matplotlib如何對每個點進行標記注釋

用annotate函數

Ⅶ 哪本python書立有蟻群演算法

簡介

蟻群演算法(ant colony optimization, ACO),又稱螞蟻演算法,是一種用來在圖中尋找優化路徑的機率型演算法。它由Marco Dorigo於1992年在他的博士論文中提出,其靈感來源於螞蟻在尋找食物過程中發現路徑的行為。蟻群演算法是一種模擬進化演算法,初步的研究表明該演算法具有許多優良的性質。針對PID控制器參數優化設計問題,將蟻群演算法設計的結果與遺傳演算法設計的結果進行了比較,數值模擬結果表明,蟻群演算法具有一種新的模擬進化優化方法的有效性和應用價值。
定義

各個螞蟻在沒有事先告訴他們食物在什麼地方的前提下開始尋找食物。當一隻找到食物以後,它會向環境釋放一種揮發性分泌物pheromone (稱為信息素,該物質隨著時間的推移會逐漸揮發消失,信息素濃度的大小表徵路徑的遠近)來實現的,吸引其他的螞蟻過來,這樣越來越多的螞蟻會找到食物。有些螞蟻並沒有像其它螞蟻一樣總重復同樣的路,他們會另闢蹊徑,如果另開辟的道路比原來的其他道路更短,那麼,漸漸地,更多的螞蟻被吸引到這條較短的路上來。最後,經過一段時間運行,可能會出現一條最短的路徑被大多數螞蟻重復著。

解決的問題

三維地形中,給出起點和重點,找到其最優路徑。

程序代碼:

numpy as npimport matplotlib.pyplot as plt%pylabcoordinates = np.array([[565.0,575.0],[25.0,185.0],[345.0,750.0],[945.0,685.0],[845.0,655.0],[880.0,660.0],[25.0,230.0],[525.0,1000.0],[580.0,1175.0],[650.0,1130.0],[1605.0,620.0],[1220.0,580.0],[1465.0,200.0],[1530.0, 5.0],[845.0,680.0],[725.0,370.0],[145.0,665.0],[415.0,635.0],[510.0,875.0],[560.0,365.0],[300.0,465.0],[520.0,585.0],[480.0,415.0],[835.0,625.0],[975.0,580.0],[1215.0,245.0],[1320.0,315.0],[1250.0,400.0],[660.0,180.0],[410.0,250.0],[420.0,555.0],[575.0,665.0],[1150.0,1160.0],[700.0,580.0],[685.0,595.0],[685.0,610.0],[770.0,610.0],[795.0,645.0],[720.0,635.0],[760.0,650.0],[475.0,960.0],[95.0,260.0],[875.0,920.0],[700.0,500.0],[555.0,815.0],[830.0,485.0],[1170.0, 65.0],[830.0,610.0],[605.0,625.0],[595.0,360.0],[1340.0,725.0],[1740.0,245.0]])def getdistmat(coordinates):num = coordinates.shape[0]distmat = np.zeros((52,52))for i in range(num):for j in range(i,num):distmat[i][j] = distmat[j][i]=np.linalg.norm(coordinates[i]-coordinates[j])return distmatdistmat = getdistmat(coordinates)numant = 40 #螞蟻個數numcity = coordinates.shape[0] #城市個數alpha = 1 #信息素重要程度因子beta = 5 #啟發函數重要程度因子rho = 0.1 #信息素的揮發速度Q = 1iter = 0itermax = 250etatable = 1.0/(distmat+np.diag([1e10]*numcity)) #啟發函數矩陣,表示螞蟻從城市i轉移到矩陣j的期望程度pheromonetable = np.ones((numcity,numcity)) # 信息素矩陣pathtable = np.zeros((numant,numcity)).astype(int) #路徑記錄表distmat = getdistmat(coordinates) #城市的距離矩陣lengthaver = np.zeros(itermax) #各代路徑的平均長度lengthbest = np.zeros(itermax) #各代及其之前遇到的最佳路徑長度pathbest = np.zeros((itermax,numcity)) # 各代及其之前遇到的最佳路徑長度while iter < itermax:# 隨機產生各個螞蟻的起點城市if numant <= numcity:#城市數比螞蟻數多pathtable[:,0] = np.random.permutation(range(0,numcity))[:numant]else: #螞蟻數比城市數多,需要補足pathtable[:numcity,0] = np.random.permutation(range(0,numcity))[:]pathtable[numcity:,0] = np.random.permutation(range(0,numcity))[:numant-numcity]length = np.zeros(numant) #計算各個螞蟻的路徑距離for i in range(numant):visiting = pathtable[i,0] # 當前所在的城市#visited = set() #已訪問過的城市,防止重復#visited.add(visiting) #增加元素unvisited = set(range(numcity))#未訪問的城市unvisited.remove(visiting) #刪除元素for j in range(1,numcity):#循環numcity-1次,訪問剩餘的numcity-1個城市#每次用輪盤法選擇下一個要訪問的城市listunvisited = list(unvisited)probtrans = np.zeros(len(listunvisited))for k in range(len(listunvisited)):probtrans[k] = np.power(pheromonetable[visiting][listunvisited[k]],alpha)*np.power(etatable[visiting][listunvisited[k]],alpha)cumsumprobtrans = (probtrans/sum(probtrans)).cumsum()cumsumprobtrans -= np.random.rand()k = listunvisited[find(cumsumprobtrans>0)[0]] #下一個要訪問的城市pathtable[i,j] = kunvisited.remove(k)#visited.add(k)length[i] += distmat[visiting][k]visiting = klength[i] += distmat[visiting][pathtable[i,0]] #螞蟻的路徑距離包括最後一個城市和第一個城市的距離#print length# 包含所有螞蟻的一個迭代結束後,統計本次迭代的若干統計參數lengthaver[iter] = length.mean()if iter == 0:lengthbest[iter] = length.min()pathbest[iter] = pathtable[length.argmin()].()else:if length.min() > lengthbest[iter-1]:lengthbest[iter] = lengthbest[iter-1]pathbest[iter] = pathbest[iter-1].()else:lengthbest[iter] = length.min()pathbest[iter] = pathtable[length.argmin()].()# 更新信息素changepheromonetable = np.zeros((numcity,numcity))for i in range(numant):for j in range(numcity-1):changepheromonetable[pathtable[i,j]][pathtable[i,j+1]] += Q/distmat[pathtable[i,j]][pathtable[i,j+1]]changepheromonetable[pathtable[i,j+1]][pathtable[i,0]] += Q/distmat[pathtable[i,j+1]][pathtable[i,0]]pheromonetable = (1-rho)*pheromonetable + changepheromonetableiter += 1 #迭代次數指示器+1#觀察程序執行進度,該功能是非必須的if (iter-1)%20==0:print iter-1# 做出平均路徑長度和最優路徑長度fig,axes = plt.subplots(nrows=2,ncols=1,figsize=(12,10))axes[0].plot(lengthaver,'k',marker = u'')axes[0].set_title('Average Length')axes[0].set_xlabel(u'iteration')axes[1].plot(lengthbest,'k',marker = u'')axes[1].set_title('Best Length')axes[1].set_xlabel(u'iteration')fig.savefig('Average_Best.png',dpi=500,bbox_inches='tight')plt.close()#作出找到的最優路徑圖bestpath = pathbest[-1]plt.plot(coordinates[:,0],coordinates[:,1],'r.',marker=u'$cdot$')plt.xlim([-100,2000])plt.ylim([-100,1500])for i in range(numcity-1):#m,n = bestpath[i],bestpath[i+1]print m,nplt.plot([coordinates[m][0],coordinates[n][0]],[coordinates[m][1],coordinates[n][1]],'k')plt.plot([coordinates[bestpath[0]][0],coordinates[n][0]],[coordinates[bestpath[0]][1],coordinates[n][1]],'b')ax=plt.gca()ax.set_title("Best Path")ax.set_xlabel('X axis')ax.set_ylabel('Y_axis')plt.savefig('Best Path.png',dpi=500,bbox_inches='tight')plt.close()

Ⅷ python 變數的命名

createPlot.ax1 是表示: ax1 是函數 createPlot 的一個屬性,這個可以在函數裡面定義也可以在函數定義後加入也可以
example:
def fun():
fun.x =1
當你在python的命令窗口下,運行一次fun()後,x 就是 fun()的一個屬性,你在命令窗口下輸入
fun.x 後面會顯示 1

也可以 在 函數定義完後加入 屬性 如 fun.y = 2,在使用 dir(fun),你就會發現fun有 x,y 這兩個屬性

Ⅸ 如何利用python的matplotlib畫圖,標記出特定位置

你的x軸輸入應該是time埃為什麼不輸入進去呢? plt.plot()第一個參數你肯定輸入了,但是第二參數沒有輸入,所以默認x軸自增,這個你直接將time數組輸入進去就可以了,plt.plot(x,y)

Ⅹ python matplotlib 繪制帶有刻度的箭頭

#繪制箭頭例子

def arrow():

plt.rcParams['font.sans-serif'] = ['SimHei']

plt.style.use('seaborn-deep')


fig = plt.figure(figsize=(16, 9),dpi=75)


ax = fig.add_subplot(121)

x=np.array([1,2,3,4])

y=np.array([2,4,6,8])

ax.plot(x,y,color = 'b')

ax.annotate("",

xy=(4.5, 9),

xytext=(4, 8),

arrowprops=dict(arrowstyle="->", color="r"))

# 設置X軸、Y軸最大坐標

ax.set_xlim(0, 10)

ax.set_ylim(0, 10)

ax.grid()

ax.set_aspect('equal')

plt.title("趨勢展示圖")

plt.show()


arrow()

熱點內容
編譯編譯有什麼 發布:2025-02-04 08:05:52 瀏覽:732
讓外網訪問內網伺服器 發布:2025-02-04 08:02:20 瀏覽:783
奶塊腳本菜地 發布:2025-02-04 07:46:35 瀏覽:238
條形碼識別源碼 發布:2025-02-04 07:45:55 瀏覽:457
mysql資料庫數據同步 發布:2025-02-04 07:41:07 瀏覽:760
安卓手機下載哪個北斗地圖 發布:2025-02-04 07:35:26 瀏覽:854
查詢伺服器ip地址代碼 發布:2025-02-04 07:08:28 瀏覽:675
python全雙工 發布:2025-02-04 06:57:46 瀏覽:196
c語言動態內存 發布:2025-02-04 06:57:06 瀏覽:78
sql倒序查詢 發布:2025-02-04 06:49:18 瀏覽:196