Python Pandas阅读CSV问题

whitzsjs  于 2023-01-28  发布在  Python
关注(0)|答案(1)|浏览(163)

我正在尝试使用Pandas读取一个没有任何标题的非结构化CSV文件。不同行的列数不同,列数没有明确的上限。现在是10,但可能会增加到15。
CSV文件内容示例:

a;b;c
a;b;c;d;e;;;f
a;;
a;b;c;d;e;f;g;h;;i
a;b;
....

下面是我如何使用Python Pandas读取它的:

pd.DataFrame(pd.read_csv(path, sep=";", header=None, usecols=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
                                            names=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'],
                                            nrows=num_of_rows + 1))

但是这会产生FutureWarning: Defining usecols with out of bounds indices is deprecated and will raise a ParserError in a future version.警告消息,我不希望我的代码因为这个原因而停止工作。
我的问题是,有没有一种方法可以使用Pandas(或任何其他等效的快速库)以未来安全的方式读取这样一个非结构化的CSV文件?

oiopk7p5

oiopk7p51#

您可以用途:

# choose a bad seperator
df = (pd.read_csv('data.csv', sep='@', header=None).squeeze()
        .str.split(';', expand=True).fillna(''))

df.columns = [chr(65+c) for c in df.columns]  # or whatever you want
print(df)

# Output
   A  B  C  D  E  F  G  H I  J
0  a  b  c                    
1  a  b  c  d  e        f     
2  a                          
3  a  b  c  d  e  f  g  h    i
4  a  b

更新

其他可能性:

df = (pd.read_csv('data.csv', sep='@', header=None).squeeze()
        .str.replace(r';{2,}', ';')
        .str.split(';', expand=True).fillna(''))
df.columns = [chr(65+c) for c in df.columns]  # or whatever you want
print(df)

# Output
   A  B  C  D  E  F  G  H  I
0  a  b  c                  
1  a  b  c  d  e  f         
2  a                        
3  a  b  c  d  e  f  g  h  i
4  a  b

相关问题