【问题标题】:Reading Data in Columns Python 2.7.3读取列中的数据 Python 2.7.3
【发布时间】:2012-06-24 02:54:13
【问题描述】:

我有一个需要阅读的数据文件。我知道要在 Python 中读取文件,您必须执行以下操作:

file = open(fileLocaion, 'r+')

但我不知道该找谁做特别阅读。我拥有的数据在列中。所以x 值在一列中,y 值在另一列中,标题位于顶部。数据(我的文本文件a.txt)看起来像

 Charge (1x), Ch A, Run #1
 Time ( s ) Charge (1x) ( µC )
 0.0000 0.021
 0.1000 0.021
 0.2000 0.021
 0.3000 0.021
 0.4000 0.021
 0.5000 0.021
 0.6000 0.021

所以第一次值是0.0000,第一次充电值是0.021。我希望能够将它带入 Python 并使用 matplotlib 来绘制它。但我无法弄清楚如何读取这些数据。

【问题讨论】:

  • 值得注意的是,在 Python 中打开文件时应该尝试使用the with statement。这既更具可读性,又消除了文件未关闭的可能性(即使发生异常)。

标签: python numpy matplotlib python-2.7 scipy


【解决方案1】:
with open('data2.txt') as f:
    f=[x.strip() for x in f if x.strip()]
    data=[tuple(map(float,x.split())) for x in f[2:]]
    charges=[x[1] for x in data]
    times=[x[0] for x in data]
    print('times',times)
    print('charges',charges)

现在费用和时间包含:

times [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6]
charges [0.021, 0.021, 0.021, 0.021, 0.021, 0.021, 0.021]

【讨论】:

    【解决方案2】:

    如果你打算用 matplotlib 绘制它,可能最简单的做法是使用 numpy.loadtxt [docs],因为无论如何你都会安装 numpy:

    >>> import numpy
    >>> d = numpy.loadtxt("mdat.txt", skiprows=2)
    >>> d
    array([[ 0.   ,  0.021],
           [ 0.1  ,  0.021],
           [ 0.2  ,  0.021],
           [ 0.3  ,  0.021],
           [ 0.4  ,  0.021],
           [ 0.5  ,  0.021],
           [ 0.6  ,  0.021]])
    

    请注意,我必须在此处添加 skiprows=2 才能跳过标题。那么时间是d[:,0] 和费用d[:,1],或者你可以用loadtxt 明确得到它们:

    >>> times, charges = numpy.loadtxt("mdat.txt", skiprows=2, unpack=True)
    >>> times
    array([ 0. ,  0.1,  0.2,  0.3,  0.4,  0.5,  0.6])
    >>> charges
    array([ 0.021,  0.021,  0.021,  0.021,  0.021,  0.021,  0.021])
    

    【讨论】:

      猜你喜欢
      • 2013-02-04
      • 2012-09-12
      • 2015-09-27
      • 2015-02-16
      • 2019-04-16
      • 1970-01-01
      • 1970-01-01
      • 2021-02-06
      • 1970-01-01
      相关资源
      最近更新 更多