【问题标题】:Collapse multiple lines when reading flat file in python在python中读取平面文件时折叠多行
【发布时间】:2018-04-26 03:57:57
【问题描述】:

我想在 python 中解析一个看起来像这样的平面文件;

  Element ID     Element Type     Result       Jacobian Sign    

============== ================= ========= =====================
      1            Parabolic      Warning          1.000000     
                  Hexahedron                                    
      2            Parabolic      Warning          1.000000     
                  Hexahedron                                    
      3            Parabolic      Warning          1.000000     
                  Hexahedron                                    
      4            Parabolic      Warning          1.000000     

我尝试使用this answer中使用的机制如下;

import pandas as pd

def parse_file(file):
    col_spec = [(0, 15), (16, 33), (34, 43), (44, 65)]
    return pd.read_fwf(file, colspecs=col_spec)

但它会读取第一行的一条记录和除了单词“Hexahedron”作为元素类型之外的另一行。

>>> data = parse_file("example.txt")
>>> data.head()
       Element ID      Element Type    Result         Jacobian Sign
0             NaN               NaN       NaN                   NaN
1  ==============  ================  ========  ====================
2               1         Parabolic   Warning              1.000000
3             NaN        Hexahedron       NaN                   NaN <= Extra record
4               2         Parabolic   Warning              1.000000

从行中可以看出,前两行被捕获为 2 条记录(记录 2 和 3)。我希望解析器将前两行捕获为一条记录,以便将短语“抛物线六面体”捕获为元素类型。我该怎么做?

【问题讨论】:

  • 展示你的尝试。解释期望的行为以及它与预期的不同之处。

标签: python parsing flat-file


【解决方案1】:

一些后处理应该可以解决问题。下面是一些使用 shift 运算符的代码。另请注意,不需要打开文件,只需将文件名传递给pd.read_fwf。

import pandas as pd

col_spec = [(0, 15), (15, 32), (32, 42), (43, 65)]
df = pd.read_fwf("example.txt", colspecs=col_spec, comment="=")

# combine rows
df["combined"] = (df['Element Type'] + df['Element Type'].shift(-1)).where(df['Element ID'].notnull(), df['Element Type'] )
# remove extra rows
df = df[df['Element ID'].notnull()]

这应该给出一个如下所示的 DataFrame:

  Element ID Element Type   Result Jacobian Sign             combined
2          1    Parabolic  Warning      1.000000  ParabolicHexahedron
4          2    Parabolic  Warning      1.000000  ParabolicHexahedron
6          3    Parabolic  Warning      1.000000  ParabolicHexahedron
8          4    Parabolic  Warning      1.000000  ParabolicHexahedron

【讨论】:

  • 太棒了!谢谢。小心使用 + 运算符连接字段。文档声明它已被弃用:pandas.pydata.org/pandas-docs/stable/…
  • 感谢有关文件的提示。我实际上是先打开文件,向前读到一个标记,然后开始解析。这是我为这篇文章清理它时留下的。
  • 您可以使用skip_blank_lines=True 和comment="=" 作为read_fwf 的参数来避免一些额外的工作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-21
  • 2018-08-18
  • 1970-01-01
  • 2012-09-29
相关资源
最近更新 更多