繁体   English   中英

将 .txt 文件读入 pandas 数据框

[英]Read .txt file into pandas dataframe

我有一个 .txt 文件。 格式是这样的:

12:12 {"name": "alice", "id":"1", "password":"123"}

12:14 {"name": "bob", "id":"2", "password":"1fsdf3"}

12:18 {"name": "claire", "id":"3", "password":"12fs3"}

我想将其转换为熊猫数据框。 列将是 [时间戳、名称、ID、密码]。 每列都会有相应的信息。 知道怎么做吗? 非常感激!

通过一次处理文件的一行来创建 DataFrame 的行。 然后,调用 DataFrame 构造函数:

import pandas as pd
import json

rows = []
with open("data.txt") as input_file:
    for line in input_file:
        line = line.strip()
        if line:
            timestamp, blob = line.split(maxsplit=1)
            # Use dict(**json.loads(blob), timestamp=timestamp) for Python <3.9
            blob = json.loads(blob) | dict(timestamp=timestamp)
            rows.append(blob)

    result = pd.DataFrame(rows)
    print(result)

这输出:

     name id password timestamp
0   alice  1      123     12:12
1     bob  2   1fsdf3     12:14
2  claire  3    12fs3     12:18

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM