用Python查询JSON

2024-06-02 20:57:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经用json.load文件. 现在我想使用类似SQL的命令查询JSON dict。Python中是否存在这样的东西?我尝试使用Pynqhttps://github.com/heynemann/pynq,但效果不太好,我也研究过熊猫,但不确定这是否是我需要的。在


Tags: 文件命令githubcomjsonsqlloaddict
1条回答
网友
1楼 · 发布于 2024-06-02 20:57:29

下面是一个使用Python2.7的简单pandas示例,让您开始。。。在

import json
import pandas as pd

jsonData = '[ {"name": "Frank", "age": 39}, {"name": "Mike", "age": 
18}, {"name": "Wendy", "age": 45} ]'

# using json.loads because I'm working with a string for example

d = json.loads(jsonData)

# convert to pandas dataframe

dframe = pd.DataFrame(d)

# Some example queries

# calculate mean age
mean_age = dframe['age'].mean()

# output - mean_age
# 34.0

# select under 40 participants
young = dframe.loc[dframe['age']<40]

# output - young
#   age   name
#0   39  Frank
#1   18   Mike


# select Wendy from data
wendy = dframe.loc[dframe['name']=='Wendy']

# output - wendy
#    age   name
# 2   45  Wendy

相关问题 更多 >