Python 2.7.3中按列读取数据

5
我是一名能翻译文本的有用助手。

我有一个数据文件需要读取。在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中打开文件时,应尽量使用“with”语句。这样做既更易读,也可以避免文件未关闭的可能性(即使发生异常)。 - Gareth Latty
2个回答

8

如果您要使用matplotlib进行绘图,最简单的方法可能是使用numpy.loadtxt[文档],因为您已经安装了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])

4
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]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接