[英]Pandas: ignore all lines following a specific string when reading a file into a DataFrame
我有一個熊貓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]
之間的文本部分,該部分是可變的(不同長度)。 標頭的長度始終相同,因此可以使用skiprows
的pandas.read_csv
。 但是, skipfooter
需要跳過的行數 ,這可以在文件之間改變。
什么是最好的解決方案? 除非沒有其他解決方案,否則我想避免從外部更改文件。
Numpy的genfromtxt能夠將生成器作為輸入(而不是直接作為文件)-生成器只要打到頁腳,就可以立即停止屈服。 生成的結構化數組可以轉換為pandas DataFrame。 這並不理想,但是看起來熊貓的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)
此方法必須對文件運行兩次。
import itertools as it
def get_footer(file_):
with open(file_) as f:
g = it.dropwhile(lambda x: x != '[Other data]\n', f)
footer_len = len([i for i, _ in enumerate(g)])
return footer_len
footer_len = get_footer('file.txt')
df = pd.read_csv('file.txt', … skipfooter=footer_len)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.