【问题标题】:How to convert a txt file with dictionary format to dataframe in python?如何将字典格式的txt文件转换为python中的数据框?
【发布时间】:2020-04-28 10:18:53
【问题描述】:

我有一个包含如下数据的文件,

{"cid": "ABCD", "text": "alphabets", "time": "1 week", "author": "xyz"}
{"cid": "EFGH", "text": "verb", "time": "2 week", "author": "aaa"}
{"cid": "IJKL", "text": "noun", "time": "3 days", "author": "nop"}

我希望阅读这个文件并创建一个类似的数据框,

cid     text    time    author
ABCD    alpha   1week   xyz
EFGH    verb    2week   aaa
IJKL    noun    3days   nop

【问题讨论】:

  • 这是文本/csv 吗?还有你是如何将这些数据放入文件中的?
  • 你看过 .keys 和 .values
  • 这是一个从应用程序生成的文本文件。
  • 如果您正在处理一个 txt 文件,请查看 json python 库以将文本转换为字典。

标签: python pandas file dictionary


【解决方案1】:

您可以尝试使用不同的分隔符将文件读取为 csv 并抓取第一列,然后应用 ast.literal_eval 转换为实际字典并转换回数据框:

import ast
output = pd.DataFrame(pd.read_csv('file.txt',sep='|',header=None).iloc[:,0]
         .apply(ast.literal_eval).tolist())

print(output)

    cid       text    time author
0  ABCD  alphabets  1 week    xyz
1  EFGH       verb  2 week    aaa
2  IJKL       noun  3 days    nop

工作示例:

file = """{"cid": "ABCD", "text": "alphabets", "time": "1 week", "author":"xyz"}
{"cid": "EFGH", "text": "verb", "time": "2 week", "author": "aaa"}
{"cid": "IJKL", "text": "noun", "time": "3 days", "author": "nop"}"""

import io #dont need for reading a file directly , just for example
import ast
print(pd.DataFrame(pd.read_csv(io.StringIO(file),sep='|',header=None).iloc[:,0]
             .apply(ast.literal_eval).tolist()))

    cid       text    time author
0  ABCD  alphabets  1 week    xyz
1  EFGH       verb  2 week    aaa
2  IJKL       noun  3 days    nop
​

【讨论】:

    猜你喜欢
    • 2019-10-28
    • 1970-01-01
    • 2022-08-22
    • 2015-07-13
    • 1970-01-01
    • 2021-07-11
    • 2021-06-16
    • 2019-05-26
    • 2023-03-16
    相关资源
    最近更新 更多