字符串后的Python图 [英] Python plot after string

查看:29
本文介绍了字符串后的Python图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从.dat文件中绘制数据.但是,此.dat文件以字符串开头.例如,我的文件包含col 1 col 2 col 3,而我想在col 3数据下读取.我想跳过两行,因为它们有字符串,并且只想在第3列下读取.如何跳过字符串?如果我们接受数据是 5x3 数据,那么我只会为 col3 绘制 (3:5,3).我能怎么做?我共享一个代码,这仅在我删除字符串时才有效.

I want to plot data from .dat file. But this .dat file starts with string. For example, My file includes col 1 col 2 col 3 and I want to read under the col 3 data. I want skip two rows because they have string and wanna read only under col 3. How can skip the strings?. If we accept the data is 5x3 data so that I will only plot (3:5,3) for col3. How can I do? I share a code and this is only working If I remove string.

  #-------input.dat---------
  #   x        y     z
  # col 1    col 2  col 3
  # 3          5      5
  # 5          6      4
  # 7          7      3
 import matplotlib.pyplot as plt
  import numpy as np
  import pylab as pl


  data = open('input.dat')
  lines = data.readlines()
  data.close()
  x1=[]
  for line in lines:
    p= line.split()
    x1.append(float(p[3]))

  xv=np.array(x1)
  plt.plot(xv)
  plt.show()

推荐答案

由于您已经在导入 numpy ,因此可以使用np.genfromtext 在这里使事情变得更简单,因为它具有选项 skip_header 告诉它要跳过多少标题行.

Since you are already importing numpy, you could use np.genfromtext here to make things a lot simpler, since it has the option skip_header which tells it how many header rows to skip.

import matplotlib.pyplot as plt
import numpy as np

data = np.genfromtxt('input.dat', skipheader=2)
xv = data[:, 2]

plt.plot(xv)
plt.show()

或者,如果您只需要阅读第 3 列:

Or, if you only need to read in column 3:

import matplotlib.pyplot as plt
import numpy as np

xv = np.genfromtxt('input.dat', skipheader=2, usecols=(2,))

plt.plot(xv)
plt.show()

这篇关于字符串后的Python图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆