我在读取文件时遇到了一些关于定义多个分隔符的问题。最初在我之前的帖子中解决了读取列标题中带有多个分隔符的文件并跳过某些行 https://stackoverflow.com/questions/45695040/reading-files-with-multiple-delimiter-in-column-headers-and-skipping-some-rows-a/45695342#45695342感谢@piRsquared
当我详细查看我的真实数据时,我
意识到某些列具有 .cd 或 .dvd 扩展名,当我应用上面的解决方案时,它们也被分离为一个新列,并且上面的解决方案开始不起作用!
b.txt
skip1
A1| A2 |A3 |A4# A5# A6 A7| A8 , A9
1,2,3,4,5.cd,6,7,8.dvd,9
1,2,3,4,5.cd,6,7,8.dvd,9
1,2,3,4,5.cd,6,7,8.dvd,9
END123
Some other data starts from here
并使用以下命令读取 b.txt 文件solution https://stackoverflow.com/questions/45695040/reading-files-with-multiple-delimiter-in-column-headers-and-skipping-some-rows-a/45695342#45695342 above
txt = open('b.txt').read().split('\nEND')[0]
pd.read_csv(
pd.io.common.StringIO(txt),
sep=r'\W+',
skiprows=1,index_col=False, engine='python')
A1 A2 A3 A4 A5 A6 A7 A8 A9
0 1 2 3 4 5 cd 6 7 8
1 1 2 3 4 5 cd 6 7 8
2 1 2 3 4 5 cd 6 7 8
A5列应该有行
5.cd
5.cd
5.cd
A9 列也是如此
8.dvd
8.dvd
8.dvd
我们应该有 A9 列,但似乎由于这种冲突它消失了。
EDIT:
我将与我的真实数据几乎相似的身份
skip rows
A1| A2| A3|A4# A5# | A6 | A7 , A8, A9 | A10 |
1 | 2 | 3 |4 # 5 # | 6.cd|7.dvd, , | 10 |
1 | 2 | 3 |4 # 5 # | 6.cd| , , 9 | 10 |
1 | 2 | 3 |4 # 5 # | |7.dvd, , | 10 |
END123
Some other data starts from here
并尝试过
txt = open('real_dat.txt').read().split('\nEND')[0]
_, h, txt = txt.split('\n', 2)
pat = r'[\|, ,#,\,]+'
names = re.split(pat, h.strip())
df=pd.read_csv(
pd.io.common.StringIO(txt),
names=names,skiprows=1,index_col=False,
engine='python')
并得到这个输出!