加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 使用pandas解析JSON文档中的一个部分

发布时间:2020-12-20 13:39:12 所属栏目:Python 来源:网络整理
导读:我正在尝试用熊猫分析我的电费账单使用情况(以 JSON格式下载的每小时数据!woot!).我能做到,但它比我想象的还要笨拙: import pandas as pdimport jsonwith open('test1.json') as f: j = json.load(f)j2 = j['DailyBillingUsage']['RegisterCollections'][
我正在尝试用熊猫分析我的电费账单使用情况(以 JSON格式下载的每小时数据!woot!).我能做到,但它比我想象的还要笨拙:

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没有任何日期或时间类型,因此无法自动转换它.搜索并猜测字符串是否为日期会导致性能下降,因此您需要自己完成.

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读