代码之家  ›  专栏  ›  技术社区  ›  jjkennedy

Pandas文本文件导入:当每个文件中存在多个表时,自动选择1个表

  •  0
  • jjkennedy  · 技术社区  · 4 月前

    在Python 3.12中使用Pandas 2.2.1,我从文本文件中导入数据,这些文件具有不同数量的元数据行和多个表,这些表位于要导入的实际数据之前。在“pd.read_csv”方法中使用“skiprows”选项时,需要跳过的行数通常在3500到4500之间。所需的数据行始终位于文本文件的末尾,并用一行破折号括起来。 文件结构(过于简化)如下:

    Archive generated by archiveSST02e.f                                                         
    GEOPHYSICAL LOG
    Borehole fluid type:                                           WATER            
    Borehole fluid resistivity/conductivity:                       see log          
    Borehole fluid temperature:                                    see log                                                                               
    CTD manufacturer and SN:                                       Sea and Sun Tech.   
    
    ***Thousands of rows of more text and tables of unused data***
    
    Then the data that is actually needed.
    The last row of dashes is the last row of the text file.
    --------------------------------------------------------------------------------------        
                                             Spec.   Spec.                                                    
            Corr.                            cond.   cond.                                                       
    Alt.     sub.     Sub.   Cond.   Temp.   CTD     formula    Press.     Dens.                                 
    feet     feet     feet   uS/cm   deg C   uS/cm   uS/cm      dbar      kg/m^3        
    --------------------------------------------------------------------------------------
    0.38     0.53     0.13    1067   26.870   1028    1030       0.04     996.93 
    0.24     0.67     0.27    1048   26.794   1012    1014       0.08     996.95
    0.12     0.79     0.38    1014   26.762    980     981       0.11     996.95
    -0.34     1.25     0.84     842   26.785    813     814       0.25     996.88
    ...
    -0.34     1.25     0.84     825   26.774    797     798       0.25     996.87
    --------------------------------------------------------------------------------------
    

    使用以下python脚本导入文本文件数据的示例脚本:

    df = pd.read_csv('Name_of_file.txt',encoding='utf-8', delimiter=r"\s+", skiprows=4196, header=None)
    

    我似乎在Stack Overflow上找不到任何东西,可以让我在不硬编码要跳过多少标题行的情况下导入所需的数据部分。我需要导入的每个文本文件都有不同数量的行要跳过,也有不同数量或行的数据要导入。

    1 回复  |  直到 4 月前
        1
  •  1
  •   León    4 月前

    您可以编写一个脚本,将数据提取到一个单独的文件中。看看 readlines() :

    with open('Name_of_file.txt', 'r', encoding='utf-8') as file:
            lines = file.readlines()
    

    现在,您有了文件中所有行的列表。获取破折号行的索引列表:(使用 https://www.w3schools.com/python/ref_string_startswith.asp )

    dash_lines = [i for i, line in enumerate(lines) if line.startswith('-')]
    

    现在,您可以轻松地获取数据开始的索引:

    start_index = dash_lines[-2] + 1  # one after second-to-last dashed line
    data_lines = lines[start_index:-1] #don't include last line, which is also dashed