Python 使用pylab打印文件中的特定列和行

Python 使用pylab打印文件中的特定列和行,python,matplotlib,Python,Matplotlib,我有一个数据文件,我想在其中绘制第二列的特定行。我的脚本如下: f=open('datafile','r') lines1=f.readlines()[4:24]#since I want the values from the 4th to the 23rd line lines2=f.readlines()[33:54]#I want the values from the 33rd to the 53rd line f.close() x1=[] y1=[] for line in l

我有一个数据文件,我想在其中绘制第二列的特定行。我的脚本如下:

f=open('datafile','r')
lines1=f.readlines()[4:24]#since I want the values from the 4th to the 23rd line
lines2=f.readlines()[33:54]#I want the values from the 33rd to the 53rd line
f.close()

x1=[]
y1=[]

for line in lines1:
    p=line.split()
    x1.append(float(p[1]))#the values are in the second column
for line in line2:
    p=line.split()
    y1.append(float(p[1]))

xv=np.array(x1)
yv=np.array(y1)

plt.plot(xv,yv)
然而,在最后我有一个错误说“x和y必须有相同的第一维度”。我对python不是很有经验,有人能给我一些建议或者让我知道我做错了什么吗?如何用不同的方法仅提取这些行

我想将第4行到第25行的x=第2列与第33行到第54行的y=第2列进行对比

事先非常感谢

问候,


Gio

您所做的错误是调用
readlines
两次

A的行为像A。调用
readlines
耗尽它。第二个调用将返回一个空列表

您可以获取一次行列表,然后使用它:

lines = f.readlines()
lines1 = lines[4:24]
lines2 = lines[33:54]
不过,看起来列表的长度会相差1,我想你需要更正一下

还请注意,您不需要将列表转换为
numpy
数组来绘制它们。

您可以使用和python切片来解决此问题:

import numpy as np
import matplotlib.pyplot as plt

x_start, x_end = 4, 25 # get values from the 4th to the 25rd line
y_start, y_end = 33, 54 # get values from the 33rd to the 54rd line

x = np.genfromtxt('datafile', usecols=(1))
y = np.genfromtxt('datafile', usecols=(1))

x = x[x_start - 1:x_end]
y = y[y_start - 1:y_end]

print ' x=', x, '\n\n y=', y

plt.plot(x, y)
plt.show()

在文本中,您指的是希望绘制某些行,但在代码中使用的行范围不同:[4:24]与“从第4行到第25行”。另外,请注意Python中的列表从0开始,因此[4:]从列表中的第五项开始。非常感谢您的帮助。事实上,我的名单彼此相差1。不管怎样,它现在确实起作用了。非常感谢你的帮助。您知道使用matplotlib和numpy处理数据的好教程吗?但是,np.genfromtxt似乎只读取一列。我怎样才能分割我的文件?上面写着“只有一列而不是一列”@gioR,原生numpy和matplotlib文档非常棒。:)另外,如果您需要解决一些问题,但不知道如何命名,我建议您使用matplotlib gallery()。记住google和stackoverflow是非常强大的组合。@gioR,np.genfromtxt在这里只读取一列(第二列的索引为1),这是因为我在本例中设置了输入参数usecols=(1)。实际上,它是读取整个文件的函数。请阅读这里的文档。@gioR,嗯,先生,请稍等。。如果您的任务通过此线程上的答案解决,请将其中一个标记为“已接受”好吗?您的声誉为+2,答案作者的声誉为+15。:)非常感谢。