【问题标题】:using pandas to parse a section inside a JSON document使用 pandas 解析 JSON 文档中的部分
【发布时间】:2014-01-18 14:18:42
【问题描述】:

我正在尝试使用 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:00read_json()的987654325@参数。

有没有办法做到这一点而不必使用变通办法? (显式读取文档,拉出子文档,调用to_datetime()函数)

【问题讨论】:

  • 你能匿名发布一些数据吗?
  • 当然,我可以做到。 (不过得等到我在家有空闲时间)

标签: python json pandas


【解决方案1】:

您可以使用我的 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 没有任何日期或时间类型,因此无法自动转换。搜索和猜测字符串是否为日期会影响性能,因此您需要自己完成。

当您发布有关您正在使用的数据的详细信息时,我将更新此答案以满足您的需求。

http://adriank.github.io/ObjectPath/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-10
    • 1970-01-01
    • 2020-10-03
    • 1970-01-01
    • 2018-06-03
    • 1970-01-01
    • 2011-12-28
    相关资源
    最近更新 更多