gpt4 book ai didi

python - 如何将存储为txt的列表导入pandas?

转载 作者:行者123 更新时间:2023-12-02 02:15:07 27 4
gpt4 key购买 nike

我有以下问题。我需要将 txt 文件加载为 pandas 数据帧。看看我的 txt 是什么样子的:

[        {
"type": "VALUE",
"value": 93.5,
"from": "2020-12-01T00:00:00.000+01",
"to": "2020-12-01T00:00:01.000+01"
},
{
"type": "VALUE",
"value": 75,
"from": "2020-12-01T00:00:01.000+01",
"to": "2020-12-01T00:05:01.000+01"
},
{
"type": "WARNING",
"from": "2020-12-01T00:00:01.000+01",
"to": "2020-12-01T00:05:01.000+01"
} ]

换句话说,我需要将txt作为字典列表来读取。然后将其作为 pandas 数据框读取。期望的输出是:

      type       value    from                             to
0 VALUE 93.5 2020-12-01T00:00:00.000+01 2020-12-01T00:00:01.000+01
1 VALUE 75 2020-12-01T00:00:01.000+01 2020-12-01T00:05:01.000+01
2 WARNING NaN 2020-12-01T00:00:01.000+01 2020-12-01T00:05:01.000+01

请问我该怎么做?我查看了这个问题,但没有帮助:Pandas how to import a txt file as a list , How to read a file line-by-line into a list?

最佳答案

import json
import pandas as pd

with open('inp_file.txt', 'r') as f:
content = json.load(f)

df = pd.DataFrame(content)

关于python - 如何将存储为txt的列表导入pandas?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67279163/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com