简体   繁体   English

Python-从txt文件绘图,跳过行

[英]Python - plot from txt file, skipping lines

I have a problem with my script. 我的脚本有问题。 I have (blabla.)txt file, for example: 我有(blabla。)txt文件,例如:

blablaba bla
dsadsadsa
dsadsadsa
50 2323
60 2839
70 9832
80 0000
.....
....
...

and script I wrote: 和我写的脚本:

import numpy as np
import matplotlib.pyplot as plt

with open("blabla.txt") as f:
    for line in xrange(3):
        next(f)
    for line in f:

      data = f.read()

      data = data.split('\n')

      x = [row.split()[0] for row in data]
      y = [row.split()[1] for row in data]

      index = [i for i,val in enumerate(x)]

      fig = plt.figure()
      ax1 = fig.add_subplot(111)
      ax1.set_title("graph")    
      ax1.set_xlabel('time')
      ax1.set_ylabel('distance')
      ax1.set_xticklabels(x)
      ax1.plot(index ,y, c='r', label='distance1')
      leg = ax1.legend()
      plt.locator_params(nbins=len(index)-1)
      plt.show()

The first question is: Is it true (syntax in the script) when I want to skip (because of the graph) the first three lines in the txt file? 第一个问题是:当我想跳过(由于图形)txt文件中的前三行时,它是真的(脚本中的语法)吗?

The second: After runscript it says: 第二个:在runscript之后说:

data = f.read()
ValueError: Mixing iteration and read methods would lose data.

What is the problem, its because of size? 有什么问题,是因为大小? (txt file has about 600 000 lines) (txt文件大约有60万行)

Thanks for all the help....Funstorm60 感谢您的所有帮助。...Funstorm60

You can use: 您可以使用:

with open("<fname>.txt", 'r') as datafile:
    __data = datafile.readlines()[3:]

data = [[float(value) for value in line.split()] for line in __data]

This will give you a 2D array of your data - although it doesn't include the index information that you've included in your question. 这将为您提供2D数据数组-尽管其中不包含问题中包含的索引信息。

EDIT: Sorry I missed the call to .split() 编辑:对不起,我错过了对.split()的呼叫

EDIT: As an example 编辑:作为一个例子

1 2 3 4
2 3 4 5
6 5 4 3

will give the output: 将给出输出:

[[1.0, 2.0, 3.0, 4.0], [2.0, 3.0, 4.0, 5.0], [6.0, 5.0, 4.0, 3.0]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM