我正在尝试使用 pandas 分析我的电费使用情况(以 JSON 格式下载的每小时数据!哇!)。我可以做到,但它比我预期的要笨拙:
import pandas as pd
import json
with open('test1.json') as f:
j = json.load(f)
j2 = j['DailyBillingUsage']['RegisterCollections']['Channel']
s = json.dumps(j2)
d = pd.read_json(s, convert_dates='ReadDate')
d.ReadDate = pd.to_datetime(d.ReadDate)
我只是期待能够做到这一点:
d = pd.read_json('test1.json', something_to_guide_pandas)
但我不能告诉它使用文档的子集 /DailyBillingUsage/RegisterCollections/Channel
,并且出于某种原因它不会自动转换 ISO 8601 格式的日期(例如 2013-12-27T04:00:00-07:00
) 即使我使用的是 read_json()
的 convert_dates
参数。
有没有办法在不使用变通方法的情况下做到这一点? (显式读取文档,拉出子文档,调用to_datetime()
函数)
最佳答案
您可以使用我的 ObjectPath 查询语言来做到这一点:
Python 方式:
$ sudo pip install objectpath
$ python
>>> from objectpath import *
>>> with open('test1.json') as f:
... j = json.load(f)
>>> tree=Tree(j)
>>> tree.execute("$.DailyBillingUsage.RegisterCollections.Channel")
-> the result here, a list of readings <-
>>> # some code to convert strings to dates
控制台方式
git clone https://github.com/adriank/ObjectPath.git
cd ObjectPath/ObjectPathPy
python ObjectPath -o file.json
(or python ObjectPath -u URLtoJSON)
>>> $.DailyBillingUsage.RegisterCollections.Channel
-> the result here, a list of readings <-
JSON 没有任何日期或时间类型,因此无法自动转换。搜索和猜测字符串是否为日期会降低性能,因此您需要自己完成。
当您发布有关您正在使用的数据的详细信息时,我会更新此答案以满足您的需求。
关于python - 使用 pandas 解析 JSON 文档中的一个部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20860846/