python - 覆盖 df.to_json 文件
问题描述
我正在使用 Python 构建一个实时 Twitter 情绪分析网络。我希望将分析结果存储在 json 格式文件中,以用作执行的每次搜索的历史数据。如何覆盖一个文件中的所有搜索数据?数据最初是临时存储在 Pandas 数据框中的,所以我将其转换为 json 中的数组
headings = ("Tweet", "Sentimen")
data = list(zip(tweets['tweet_text'], sentiment))
df = pd.DataFrame(data, columns=['Tweet', 'Sentimen'])
df.to_json(r'Export_DataFrame6.json', orient='records', indent=4)
a_file = open("Export_DataFrame6.json", "r")
json_object = json.load(a_file)
d = json_object[0]
d['Tweet'] = "Testing"
d['Sentimen'] = "Negative"
a_file = open("Export_DataFrame6.json", "w")
json.dump(json_object, a_file)
a_file.close()
更新代码:
headings = ("Tweet", "Sentimen")
data = list(zip(tweets['tweet_text'], sentiment))
df = pd.DataFrame(data, columns=['Tweet', 'Sentimen'])
df.to_json(r'Export_DataFrame6.json', orient='records', indent=4)
a_file = open("Export_DataFrame6.json", "r")
json_object = json.load(a_file)
a_file.close()
d = json_object[0]
d['Tweet'] = tweets['tweet_text']
d['Sentimen'] = sentiment
a_file = open("Export_DataFrame6.json", "w")
json.dump(json_object, a_file)
a_file.close()
错误:TypeError:Series 类型的对象不是 JSON 可序列化的
解决方案
我认为你被困在这条线上:
d = json_object[0]
因为您认为您有一个 json 对象但没有,并且当您尝试使用 [0] 时会收到错误消息。没有看到json文件,这是一个粗略的猜测。
你能这样打开你的文件吗?
with open('Export_DataFrame6.json', 'rb') as f:
json_object = f.read().decode('utf-8')
然后尝试
d = json_object[0]
or
d = json.loads(json_object)[0]
推荐阅读
- pyspark - 使用两个日期列作为范围匹配日期
- python - 如何使用 Selenium WebDriver (Chrome) 打开页面,而无需等待它在 Python 中加载?
- css - 垫颜色不透明度的第二个参数是什么?
- java - 将两个数组按升序与数组内的未知值组合
- excel - 使用 VBA 将 CustomDocumentProperties 从 Word 导入 Excel
- c# - WinForms 错误:无法从传输连接读取数据:现有连接被远程主机强行关闭
- php - 在多个数组中按键排序
- python-3.x - 如何使用 Python3 将输入字符串“DC501GCCCA098911”排序为输出:“CD015ACCCG011899”?
- node.js - JWT 登录发布请求返回不正确的密码错误
- php - 需要有关 PHP 和 HTML 的帮助