[英]Read .txt file into pandas dataframe
I have a .txt file.我有一个 .txt 文件。 The format is like this:格式是这样的:
12:12 {"name": "alice", "id":"1", "password":"123"}
12:14 {"name": "bob", "id":"2", "password":"1fsdf3"}
12:18 {"name": "claire", "id":"3", "password":"12fs3"}
I want to convert it to a pandas dataframe.我想将其转换为熊猫数据框。 The columns would be [timestamp, name, id, password].列将是 [时间戳、名称、ID、密码]。 Each column would have the corresponding information.每列都会有相应的信息。 Any idea how to do it?知道怎么做吗? Much appreciated!非常感激!
Create the rows of the DataFrame by processing one line of the file at a time.通过一次处理文件的一行来创建 DataFrame 的行。 Then, call the DataFrame constructor:然后,调用 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)
This outputs:这输出:
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.