python - 读取列中的数据 Python 2.7.3

标签 python numpy matplotlib python-2.7 scipy

我有一个数据文件,我需要阅读它。我知道要用 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/

相关文章:

python - 在 python 3 中,如何将 bytes 对象中的单个字节放入列表而不将它们转换为整数?

python - Optparse 和很多 if not

python - train_test_split上的Pandas 'Passing list-likes to .loc or [] with any missing labels is no longer supported'返回数据

python - 我怎样才能在给定可能元素的每个可能的长度 L 数组的数组上快速运行一个函数?

python - 从一维图到二维掩模

python - wxPython 内部 : two created threads after calling app. MainLoop()

python - Dask Dataframe 独特操作 : Worker running out of memory (MRE)

python - 使用自定义数据类型时 Numpy 中出现类型错误

python - matplotlib 基线倾斜的 3d 多边形图

python - matplotlib 直方图中的圆条