python - 打开 JSON txt 文件并将其设置为 DataFrame 时发生 KeyError
问题描述
我有一个代码,它给了我一个没有保存推文的空 DataFrame。我试图通过print(line)
在 json 文件中的 for 行下进行调试:和json_data = json.loads(line)
. 这导致了一个KeyError
. 我如何解决它?谢谢你。
list_df = list()
# read the .txt file, line by line, and append the json data in each line to the list
with open('tweet_json.txt', 'r') as json_file:
for line in json_file:
print(line)
json_data = json.loads(line)
print(line)
tweet_id = json_data['tweet_id']
fvrt_count = json_data['favorite_count']
rtwt_count = json_data['retweet_count']
list_df.append({'tweet_id': tweet_id,
'favorite_count': fvrt_count,
'retweet_count': rtwt_count})
# create a pandas DataFrame using the list
df = pd.DataFrame(list_df, columns = ['tweet_id', 'favorite_count', 'retweet_count'])
df.head()
解决方案
您的评论说您正在尝试保存到文件,但您的代码有点说您正在尝试从文件中读取。以下是如何做到这两点的示例:
写入 JSON
import json
import pandas as pd
content = { # This just dummy data, in the form of a dictionary
"tweet1": {
"id": 1,
"msg": "Yay, first!"
},
"tweet2": {
"id": 2,
"msg": "I'm always second :("
}
}
# Write it to a file called "tweet_json.txt" in JSON
with open("tweet_json.txt", "w") as json_file:
json.dump(content, json_file, indent=4) # indent=4 is optional, it makes it easier to read
注意w
(如写)中的open("tweet_json.txt", "w")
。您正在使用r
(如在阅读中),它不允许您写任何东西。还要注意使用json.dump()
而不是json.load()
。然后我们得到一个看起来像这样的文件:
$ cat tweet_json.txt
{
"tweet1": {
"id": 1,
"msg": "Yay, first!"
},
"tweet2": {
"id": 2,
"msg": "I'm always second :("
}
}
从 JSON 读取
让我们使用 pandas 读取我们刚刚编写的文件read_json()
:
import pandas as pd
df = pd.read_json("tweet_json.txt")
print(df)
输出如下所示:
>>> df
tweet1 tweet2
id 1 2
msg Yay, first! I'm always second :(
推荐阅读
- html - 根据 BEM,SASS 中的类命名标准应该是什么?类名应该以大写字母还是小写字母开头?
- mysql - MySQL连接节点
- ceph - Rados 网关安装 (CEPH)
- regex - 需要获取文件中与模式匹配的所有字符串(Perl)
- csv - Nifi ValideCSV 模式示例
- java - Spring Cloud Stream Source - 不拉取
- keras - Keras:“找到属于 5 个类别的 322 张图像。”
- r - 如何在 RStudio 窗口模式下设置闪亮的应用程序大小?
- c# - 如何使我的自定义控件在 Xamarin 窗体中浮动?
- node.js - 错误 [MongoError]: 首次连接时无法连接到服务器 [cluster0.4mocw.gcp.mongodb.net:27017]