如何解决分隔符冲突

发布于 2025-01-11 00:16:53 字数 919 浏览 4 评论 0原文

我有一个很大的 .TXT 文件,由“;”分隔。不幸的是我的一些值包含“;”同样,在这种情况下,它不是分隔符,但被 pandas 识别为分隔符。因此,我很难阅读 .txt。文件写入 pandas 中,因为某些行比其他行有更多的列。背景:我试图将多个 .txt 文件合并到 1 个数据帧中,并收到以下错误:ParserError:标记数据时出错。 C 错误:第 443 行中预期有 21 个字段,结果看到了 22 个字段。

因此,在检查第 443 行时,我确实看到该行还有 1 个“;”实例因为它是价值观之一的一部分。

复制:

文本文件 1:

1;2;3;4
23123213;23123213;23123213;23123213
123;123;123;123
123;123;123;123
1;1;1;1
123;123;123;123
12;12;12;12
3;3;3;3

文本文件 2:

1;2;3;4
23123213;23123213;23123213;23123213
123;123;123;123
123;123;12;3;123
1;1;1;1
123;123;123;123
12;12;12;12
3;3;3;3

代码:

import pandas as pd
import glob
import os

path = r'C:\Users\file'
all_files = glob.glob(path + "/*.txt")
li = []
for filename in all_files:
    df = pd.read_csv(filename, index_col=None, header=0, delimiter=';')
    li.append(df)
frame = pd.concat(li, axis=0, ignore_index=True)

I have a large .TXT file which is delimited by ";". Unfortunately some of my values contain ";" aswell, which in that case is not a delimiter but recognized as delimiter by pandas. Becasue of this I have difficulties reading the .txt. files into pandas because some lines have more columns than the others. Background: I am trying to combine several .txt files into 1 dataframe and get the following error: ParserError: Error tokenizing data. C error: Expected 21 fields in line 443, saw 22.

So when checking line 443 I saw indeed that that line had 1 more instance of ";" because it was part of one of the values.

Reproduction:

Text file 1:

1;2;3;4
23123213;23123213;23123213;23123213
123;123;123;123
123;123;123;123
1;1;1;1
123;123;123;123
12;12;12;12
3;3;3;3

Text file 2:

1;2;3;4
23123213;23123213;23123213;23123213
123;123;123;123
123;123;12;3;123
1;1;1;1
123;123;123;123
12;12;12;12
3;3;3;3

Code:

import pandas as pd
import glob
import os

path = r'C:\Users\file'
all_files = glob.glob(path + "/*.txt")
li = []
for filename in all_files:
    df = pd.read_csv(filename, index_col=None, header=0, delimiter=';')
    li.append(df)
frame = pd.concat(li, axis=0, ignore_index=True)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文