Skip to main content
 首页 » 编程设计

python之结合多个 Pandas read_csv 和/或 file.readline()

2025年05月04日7jackei

我正在尝试读取一个文本数据文件,它由许多连续和交替的数据 block 组成,每个 block 要么有 N 行 X 列,要么有 N+1 行和 Y 列。

我的想法是使用 pd.read_csv 进行两次连续调用,第一次使用选项 nrow=N,第二次使用 nrow=N+1 ,但是我发现了这个我不明白的问题。

让我们考虑这个最小的例子:

#header first line 
#header second line 
-2.000000000000e+00 7.853981633974e-03 
-1.998000000000e+00 7.853981633974e-03 
-1.999000000000e+00 1.570796326795e-05 8.214081241617e-13 8.222110115758e-18 6.069302089412e+00 3.450000000000e+07 3.077971152413e+03 0.000000000000e+00 0.000000000000e+00 -6.315974034994e+02 0.000000000000e+00 0.000000000000e+00 1.000000000000e+00 0.000000000000e+00 0.000000000000e+00 -1.000000000000e+00 8.526515773580e+06 2.736441000000e+03  

这是我用来读取数据的代码:

import pandas as pd 
fp=open('test.txt') 
fp.readline()#let's skip first and second line 
fp.readline() 
q=pd.io.parsers.read_csv(fp,nrows=2,header=None,sep=' ',names=['x_ar','a_ar']) 

现在,我期待进一步的结果:

In [4]: fp.readline() 

将是最后一行,但是,我得到一个空字符串。

Out[4]: '' 

这是怎么回事?我该如何解决这个问题?

附言。我知道我可以使用 fp.readline 进行迭代,但我对 pandas 解决方案很感兴趣。

请您参考如下方法:

  1. 关于最后一个fp.readline()中的空字符串:

When you open a file with open(filepath) a file handle iterator is returned. An iterator is good for one pass through its contents. So pd.io.parsers.read_csv(fp,nrows=2,header=None,sep=' ',names=['x_ar','a_ar']) reads the contents and exhausts the iterator. Subsequent calls to pd.read_csv thinks the iterator is empty.

Answer adapted from this question.

  1. 要处理文件顶部的注释,您可以像这样传递 comments='#':
fp=open('../test.txt') 
pd.io.parsers.read_csv(fp,nrows=2,header=None,sep=' ',names=['x_ar','a_ar'], comment='#') 

你的输出将是:

     x_ar   a_ar 
0   -2.000  0.007854 
1   -1.998  0.007854