gpt4 book ai didi

python - 读取列标题中包含多个定界符的文件并在末尾跳过某些行

转载 作者:太空宇宙 更新时间:2023-11-03 12:55:04 25 4
gpt4 key购买 nike

我是 Python 的新手,我想使用 pandas 来读取数据。我已经做了一些搜索和努力来解决我的问题,但我仍然在挣扎。提前感谢您的帮助!

我有一个类似这样的.txt 文件;

skip1
A1| A2 |A3 |A4# A5# A6 A7| A8 , A9
1,2,3,4,5,6,7,8,9
1,2,3,4,5,6,7,8,9
1,2,3,4,5,6,7,8,9

END***
Some other data starts from here

首要任务是我想指定 A1、A2、A3、A4、A5、A6、A7、A8 和 A9 作为列名。但是,有多个分隔符,例如 ' ','|','#',这使得在读取文件时分配分隔符很麻烦。我试过这样;

import pandas as pd
import glob
filelist=glob.glob('*.txt')
print(filelist)

df = pd.read_csv(filelist,skiprows=1,skipfooter=2,skipinitialspace=True, header=0, sep=r'\| |,|#',engine='python')

但是我查看Spyder的data explorer df时好像没有任何反应。

第二个任务是在读取过程中删除我不需要的以 END*** 行开头的数据。 header 始终具有相同的长度。但是,skipfooter 需要跳过的行数,这应该在文件之间更改。

已经问了几个问题,但似乎我无法让它们解决我的问题!

how-to-read-txt-file-in-pandas-with-multiple-delimiters

pandas-read-delimited-file?

import-text-to-pandas-with-multiple-delimiters

pandas-ignore-all-lines-following-a-specific-string-when-reading-a-file-into-a

编辑:关于删除读数,删除以 END 行开头的数据

如果b.txt文件是这样的b.txt

skip1
A1| A2 |A3 |A4# A5# A6 A7| A8 , A9
1,2,3,4,5,6,7,8,9
1,2,3,4,5,6,7,8,9
1,2,3,4,5,6,7,8,9

END123
Some other data starts from here

使用下面的第二种解决方案;

txt = open('b.txt').read().split('\nEND')[0]
_, h, txt = txt.split('\n', 2)
pat = r'[\|, ,#,\,]+'
names = re.split(pat, h.strip())

pd.read_csv(
pd.io.common.StringIO(txt),
names=names, header=None,
engine='python')

得到这个,

   A1  A2  A3  A4  A5  A6  A7  A8  A9
0 1 2 3 4 5 6 7 8 9
1 1 2 3 4 5 6 7 8 9
2 1 2 3 4 5 6 7 8 9

最佳答案

拆分文件,然后从字符串中读取

txt = open('test.txt').read().split('\nEND***')[0]
pd.read_csv(
pd.io.common.StringIO(txt),
sep=r'\W+',
skiprows=1, engine='python')

A1 A2 A3 A4 A5 A6 A7 A8 A9
0 1 2 3 4 5 6 7 8 9
1 1 2 3 4 5 6 7 8 9
2 1 2 3 4 5 6 7 8 9

我们可以非常明确地解析头部并将文件的其余部分解析为csv

txt = open('test.txt').read().split('\nEND***')[0]
_, h, txt = txt.split('\n', 2)
pat = r'[\|, ,#,\,]+'
names = re.split(pat, h.strip())

pd.read_csv(
pd.io.common.StringIO(txt),
names=names, header=None,
engine='python')

A1 A2 A3 A4 A5 A6 A7 A8 A9
0 1 2 3 4 5 6 7 8 9
1 1 2 3 4 5 6 7 8 9
2 1 2 3 4 5 6 7 8 9

关于python - 读取列标题中包含多个定界符的文件并在末尾跳过某些行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45695040/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com