读取Python2.7.3列中的数据

2024-04-20 10:36:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据文件,需要阅读。我知道要阅读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来绘制它。但是我很难弄清楚如何读取这些数据。


Tags: 文件数据runtxt标题timematplotlib数据文件
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])
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]

相关问题 更多 >