如何使用熊猫将非结构化平面文件导入Python?

问题描述 投票:0回答:1

我正在尝试将.db文件导入熊猫。该文件按以下顺序排序:


Person 1

Characteristic 1: Value 

Characteristic 2: Value


Person 2

Characteristic 1: Value

Etc


我想将数据导入大熊猫,并在这样的列中将人作为具有不同特征的行:


Person Characteristic 1 Characteristic 2

Person 1 Value Value

Person 2 Value Value

Etc


我曾尝试环顾四周,但只发现了导入普通平面文件的建议,其中导入之前已经在文件中指定了列。

任何帮助将不胜感激。

python pandas python-import flat-file flat
1个回答
0
投票

假设:

  • 输入是面向行的文本文件
  • 空行将被忽略
  • 不包含冒号(':')的行声明新记录
  • 包含冒号的行声明当前记录的属性

这不是熊猫可以直接处理的文件格式,但是Python可以轻松地建立记录列表,稍后将提供数据框:

records = []
current = None
fieldnames = ['Person']

with open('inputfile') as file:
    for line in file:
        line = line.strip()
        if len(line) != 0:            # ignore empty lines
            if ':' in line:           # a characteristic line
                attr, value = line.split(':', 1)
                attr = attr.strip()
                current[attr] = value.strip()
                if not attr in fieldnames:
                    fieldnames.append(attr)
            else:                                      # a person line
                current = {'Person': line}
                records.append(current)

df = pd.DataFrame(columns = fieldnames, data = records)

使用您的样本数据,可以得到预期的结果:

     Person Characteristic 1 Characteristic 2
0  Person 1            Value            Value
1  Person 2            Value              NaN
© www.soinside.com 2019 - 2024. All rights reserved.