我有一个 pandas DataFrame,可以总结为:
[Header]
Some_info = some_info
[Data]
Col1 Col2
0.532 Point
0.234 Point
0.123 Point
1.455 Square
14.64 Square
[Other data]
Other1 Other2
Test1 PASS
Test2 FAIL
我的目标是只读取 [Data] 和 [Other data] 之间的文本部分,这是可变的(不同长度)。 header 的长度始终相同,因此可以使用 pandas.read_csv 中的 skiprows。但是,skipfooter 需要跳过行数,这可以在文件之间改变。
这里最好的解决方案是什么?我想避免在外部更改文件,除非没有其他解决方案。
请您参考如下方法:
Numpy 的 genfromtxt 能够将生成器作为输入(而不是直接将文件作为输入)——生成器可以在到达您的页脚后立即停止生成。生成的结构化数组可以转换为 pandas DataFrame。这不是很理想,但看起来 pandas 的 read_csv 不能直接带生成器。
import numpy as np
import pandas as pd
def skip_variable_footer(infile):
for line in infile:
if line.startswith('[Other data]'):
raise StopIteration
else:
yield line
with open(filename, 'r') as infile:
data = np.genfromtxt(skip_variable_footer(infile), delimiter=',', names=True, dtype=None)
df = pd.DataFrame(data)
