我有一个文本文件,其中的数据由缩进分隔.我想从数据中创建一个数据帧.缩进分隔id,然后在每个id中有不同的集合,每个集合都有其数据,其中的字段如"Main\u id"、"Secondary\u id"、"Type"、"Value"、"Start\u Date"、"End Date"将重复"Category"和"Capacity"(如果多次出现).

我需要一个循环,但我不知道如何重复一些数据,而不是其他数据.请问有什么指示/建议吗?

    with open('test.txt') as file:
        data = file.read()
    list_sep=data.split('\i')
    list_1=list_sep[1].split('\n')
    q_columns=["Id", "set","Main_id", "Secondary_id","Quantity", "Type",
           "Value", "Category", "Capacity", "Start Date", "End Date"]
    df_q=pd.DataFrame(columns=q_columns)

示例文本文件:

Total ids entered : 3
Id :  6050
 set count = 1
    set : 256
               Main_id : 5677002
               Secondary_id : 34248              
               Quantity : 6
               Type : AB12
               Value : crypt
               Category : DFR
               Capacity : 100
               Category: BAS
               Capacity: 500
               Start_Date : 04/01/2022
               End_Date : 1/31/2023
Id : 123 
 set count = 2
    set : 456
               Main_id : 123456789
               Secondary_id : 101112131               
               Quantity : 4
               Type : AB12
               Value : crypt
               Category : DFR
               Capacity : 100
               Start_Date : 04/01/2022
               End_Date : 1/31/2023
               
    set : 789
               Main_id : 675497072432
               Secondary_id : 265902648927
               Quantity : 1
               Type : MAC12
               Value : nocl
               Category : DFR
               Capacity : 200
               Quantity : 2
               Type : GC56
               Value : crypt
               Category : BAS
               Capacity : 300
               Start_Date : 01/01/2023
               End_Date : 01/31/2023
               
Id :  897
 set count = 1
    set : 956
               Main_id : gy4567890
               Secondary_id : ky234248              
               Quantity : 6
               Type : MAB13
               Value : nocl
               Category : gcl
               Capacity : 100
               Start_Date : 04/01/2022
               End_Date : 1/31/2023
           

Looking for this Output: enter image description here

推荐答案

这比看起来要复杂得多.这是我的方法.这远非最佳,但应该给你一个 idea :

from collections import defaultdict
import pandas as pd

# read the file line by line
with open("test.txt", "r", encoding="utf-8") as file:
    data = file.read()

# define everything between two ids as an item
items = data.split("Id :")[1:]

all_items = []
for item in items:
    lines = [l.strip() for l in item.split("\n")]
    parsed_items = defaultdict(list)
    parsed_items["Id"].append(lines[0])
    for line in lines:
        if ":" not in line:
            continue
        key, value = (item.strip() for item in line.split(":"))
        parsed_items[key].append(value)

    # now fill the duplicate rows with the last values
    max_entries = max([len(v) for v in parsed_items.values()])
    for key, value in parsed_items.items():
        for _ in range(max_entries - len(value)):
            parsed_items[key].append(value[-1])
    all_items.append(parsed_items)

df = pd.concat([pd.DataFrame(i) for i in all_items], ignore_index=True)

# if desired, can filter the relevant columns
q_columns = ["Id", "set", "Main_id", "Secondary_id", "Quantity", "Type",
             "Value", "Category", "Capacity", "Start_Date", "End_Date"]
df = df[q_columns]

Python相关问答推荐

将DF中的名称与另一DF拆分并匹配并返回匹配的公司

Python多处理:当我在一个巨大的pandas数据框架上启动许多进程时,程序就会陷入困境

韦尔福德方差与Numpy方差不同

如何在Python中将returns.context. DeliverresContext与Deliverc函数一起使用?

为什么符号没有按顺序添加?

如何使用根据其他值相似的列从列表中获取的中间值填充空NaN数据

Django REST Framework:无法正确地将值注释到多对多模型,不断得到错误字段名称字段对模型无效'<><>

pandas:排序多级列

SQLAlchemy bindparam在mssql上失败(但在mysql上工作)

从Windows Python脚本在WSL上运行Linux应用程序

如何在TensorFlow中分类多个类

为什么常规操作不以其就地对应操作为基础?

重置PD帧中的值

从源代码显示不同的输出(机器学习)(Python)

如何合并具有相同元素的 torch 矩阵的行?

如何使用Azure Function将xlsb转换为xlsx?

需要帮助使用Python中的Google的People API更新联系人的多个字段'

一维不匹配两个数组上的广义ufunc

使用美汤对维基百科表格进行网络刮擦未返回任何内容

IpyWidget Select 框未打开