我有一个数据文件,我需要阅读它。我知道要用 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
绘制它。但我无法弄清楚如何读取这些数据。
最佳答案
如果您要使用 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
才能跳过 header 。那么时间是 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])
关于python - 读取列中的数据 Python 2.7.3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11145499/