当前位置:首页 » 编程语言 » 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 10:00:55 浏览:27
javaip端口 发布:2025-02-04 09:27:09 浏览:856
国产存储科技进步二等奖 发布:2025-02-04 09:13:00 浏览:693
编程课v 发布:2025-02-04 08:45:00 浏览:108
模拟器能有手机脚本么 发布:2025-02-04 08:39:50 浏览:760
android显示html图片 发布:2025-02-04 08:35:31 浏览:793
如何查学信网账号及密码 发布:2025-02-04 08:33:55 浏览:504
linux32位jdk 发布:2025-02-04 08:33:55 浏览:249
康佳服务器连接失败是怎么回事 发布:2025-02-04 08:18:51 浏览:918
编译编译有什么 发布:2025-02-04 08:05:52 浏览:737