检查列不一致的文本文件中的分隔符,(逗号),并在Python中将数据添加到Excel

问题描述 投票:0回答:1

我有许多带有分隔符

,
的文本文件,如下所示。 文本文件的示例:

a,
b,
c,
a,d,b,
k,m,
f,g,h,j,

我需要在 Excel 文件中输出,每个文本文件位于不同的工作表中。当

pd.read_table
遇到列中大小不一致时,例如在文本文件的第 4 行中,它表示预期 2 个字段看到 4,我收到解析器错误。

a
b
c
a d b
k m
f g h j

我正在使用以下代码:

df = pd.read_table("exp.text",delimeter = ",", header=None)
python pandas excel dataframe csv
1个回答
0
投票

您的问题来自于您的字段数量不固定。

我看到两个选择。您可以提前知道列数(或至少一个上限)并且可以指定列:

N_COLs = 10
df = (pd.read_csv(your_file, sep=',', names=range(N_COLs))
        .dropna(how='all', axis=1) # optional, to drop empty columns
     )

或者你不这样做,你可以传递一个虚拟的不存在的分隔符来获得单个列,然后

split
:

df = (pd.read_csv(your_file, sep='--NOSEP--', header=None, engine='python')[0]
        .str.strip(', ').str.split(',', expand=True)
     )

输出:

   0     1     2     3
0  a  None  None  None
1  b  None  None  None
2  c  None  None  None
3  a     d     b  None
4  k     m  None  None
5  f     g     h     j
© www.soinside.com 2019 - 2024. All rights reserved.