在Python中拆分.dat文件以进行绘图



我有一个.dat文件,我想在该文件中绘制一些数据。我使用nom1 = open('file1.dat','rb').readlines()[3:] 删除了文件的前几行

删除行后,.dat文件看起来像这样:

Flow  2012  9 22 24  0  230.0000      354.0856
Flow  2012  9 23 24  0  231.0000      353.0887
Flow  2012  9 24 24  0  236.0000      357.0877
Flow  2012  9 25 24  0  235.0000      358.0837

总共应该有8列,但它将每一行读取为一大组字母和数字。我想画出时间,它在"第2、3和4列"(例如2012/9/22),与第7和第8列相对。我曾想过使用分割函数nom2=nom1.split(),但在说AttributeError: 'list' object has no attribute 'split'时出错。下一个想法是尝试使用空白描绘,但对如何进行没有真正的好主意。如果有更快、更有效的方法,请告诉我。另外,如果我说得太含糊,请告诉我。

感谢

>>> file = open(r"class X.txt")
>>> type(file.readlines())
<class 'list'>

所以readlines返回一个列表?因此,很明显,对其进行切片表示将跳过列表中的前3项。但这份名单上到底有什么?

>>> for line in file.readlines():
    print(type(line))   
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>

所以每一行都是作为一个单独的字符串读取的!这意味着[3:]将跳过文件中的前3行,而不是列。好的,但是我们怎样才能得到实际的列呢?

>>> for line in file.readlines():
    print(line.split())  
['Flow', '2012', '9', '22', '24', '0', '230.0000', '354.0856']
['Flow', '2012', '9', '23', '24', '0', '231.0000', '353.0887']

好的,到了那里,我们只需将每个单独的字符串(行)拆分为存储在列表中的多个字符串。现在,我们可以通过执行[3:]来跳过前3列。我们需要一个地方来拯救它。在列表中,每个元素都是我们需要的列的列表,怎么样?

>>> interesting = []
>>> for line in file.readlines():
    interesting.append(line.split()[3:])
>>> interesting
[['22', '24', '0', '230.0000', '354.0856'], ['23', '24', '0', '231.0000', '353.0887'], ['24', '24', '0', '236.0000', '357.0877'], ['25', '24', '0', '235.0000', '358.0837']]
>>> interesting[0]
['22', '24', '0', '230.0000', '354.0856']

瞧,我们来了。仔细想想,希望它能让自己变得非常清楚。

首先读取csv文件,然后进行拆分。

file = pd.read_csv('path/file.dat',header = None)

最新更新