【发布时间】:2021-03-13 10:02:37
【问题描述】:
我有一个目录中的 .ASC 数据文件被另一个程序写入其中,数据看起来像这样
数据在多个文件中,其中 cmets 以“/”开头,标题在文件中出现多次,但我只想为所有数据行保留一个标题。
最终目标是在将整个数据文件写入目录后立即将其加载到 Pandas Dataframe 中。我只在一个文件上尝试过简单的 Pandas read_csv
import pandas as pd
df=pd.read_csv("demo.txt", header = None, sep = "\s+",comment='/')
df.head()
得到如下结果:
后来我尝试使用传统的 python 读取文件操作,该操作有效,但部分您可以看到它跳过了很多行。
f = open("demo.txt", "r")
for i in f:
if not (f.readline(1)=='/'):
f2 = open("demofile2.txt", "a")
f2.write(f.readline())
f2.close()
the algorithm could be:
read one file or multiple files or as soon as a new file written into the directory
read it directly as .ASC if not change to . TXT a
keep the headers in the first row and discard all the comments.
注意:我已手动将类型 .ASC 更改为 .TXT,
更新:尝试添加可以在本地复制粘贴的较小数据集
/comments start
/comments end
/id h1 h2 h3 Date h5
0 1 41 0 12/4/2018 0
1 1 0 0 12/4/2018 0
2 1 0 0 12/4/2018 0
3 1 0 0 12/4/2018 0
4 1 90 0 12/4/2018 0
/comments start
/comments end
/id h1 h2 h3 Date h5
5 1 41 0 12/4/2018 0
6 1 0 0 12/4/2018 0
7 1 0 0 12/4/2018 0
8 1 0 0 12/4/2018 0
9 1 90 0 12/4/2018 0
希望它看起来像这样:
id h1 h2 h3 Date h5
0 1 41 0 12/4/2018 0
1 1 0 0 12/4/2018 0
2 1 0 0 12/4/2018 0
3 1 0 0 12/4/2018 0
4 1 90 0 12/4/2018 0
5 1 41 0 12/4/2018 0
6 1 0 0 12/4/2018 0
7 1 0 0 12/4/2018 0
8 1 0 0 12/4/2018 0
9 1 90 0 12/4/2018 0
注意这个模式在文件中重复了好几次,即 cmets,->headers->data cmets->headers->data 等等。并且目录中有多个文件。
【问题讨论】:
-
请注意,您的日期中也有
/,这就是pandas.read_csv不适合您的原因 -
是的,这就是为什么我尝试了另一种方法,首先只在开头删除“/”,然后将其转换为 pandas 数据框,但问题是这种方法跳过了很多行
-
您能否提供一个表格的复制粘贴示例(图像对此无用)?然后我们可以自己尝试一下。
-
@Thymen 实际上试图找到一种方法来放置 csv 或 .asc 数据,但我在这个问题中找不到任何方法来加载它
-
@awaisumar 您能否将图像示例作为代码块提供(如果以下答案尚未解决您的问题)?
标签: python-3.x pandas data-science