[英]How to parse this JSON data to list in Python?
I have a json file which looks like this: 我有一个看起来像这样的json文件:
[{"lat":51.877743,"lng":-0.4116338,"acc":0,"time":0},`{"lat":51.877743,"lng":-0.4116338,"acc":20,"time":1465386382293},{"lat":51.877743,"lng":-0.4116338,"acc":20,"time":1465386412347}, ...`
I read them using the following code: 我使用以下代码阅读它们:
import json
with open('data.json') as data_file:
data = json.load(data_file)
and the data looks like this: 数据看起来像这样:
data
Out[18]:
[{u'acc': 0, u'lat': 51.877743, u'lng': -0.4116338, u'time': 0},
{u'acc': 20, u'lat': 51.877743, u'lng': -0.4116338, u'time': 1465386382293L},
{u'acc': 20, u'lat': 51.877743, u'lng': -0.4116338, u'time': 1465386412347L},
I want to extract the 'lat' and 'lng' fields into a list like this: 我想将“ lat”和“ lng”字段提取到这样的列表中:
array([[ 0.37291534, 0.90496579],
[ 0.43889613, 0.62523318],
[ 0.96554937, 0.73811836],
[ 0.9254325 , 0.51556322],
[ 0.26246525, 0.01470611],
[ 0.73168115, 0.99624888],
[ 0.38049958, 0.28766334],
[ 0.94917181, 0.60546656],
[ 0.52672308, 0.60608954],
[ 0.03778316, 0.92360363]])
How can I do it? 我该怎么做?
pandas approach: 熊猫方法:
import pandas as pd
In [109]: df = pd.DataFrame(data)
In [110]: df
Out[110]:
acc lat lng time
0 0 51.877743 -0.411634 0
1 20 51.877743 -0.411634 1465386382293
2 20 51.877743 -0.411634 1465386412347
In [111]: df[['lat','lng']]
Out[111]:
lat lng
0 51.877743 -0.411634
1 51.877743 -0.411634
2 51.877743 -0.411634
In [112]: df[['lat','lng']].values
Out[112]:
array([[ 51.877743 , -0.4116338],
[ 51.877743 , -0.4116338],
[ 51.877743 , -0.4116338]])
You can try something along these lines: 您可以尝试以下方法:
what_you_want = [[e['lat'], e['lng']] for e in data]
This can further be converted to array, or better yet, to a numpy.array
. 可以将其进一步转换为array,或者更好的是,转换为
numpy.array
。
I cannot help but to also suggest that you take a look at pandas.DataFrame
. 我不禁要建议您看看
pandas.DataFrame
。
You could simply use a list comprehension: 您可以简单地使用列表理解:
>>> [[i['lat'], i['lng']] for i in data]
[[51.877743, -0.4116338], [51.877743, -0.4116338], [51.877743, -0.4116338]]
To get your stylized array, use numpy
要获取风格化的数组,请使用
numpy
>>> import numpy as np
>>> np.array([[i['lat'], i['lng']] for i in data])
array([[ 51.877743 , -0.4116338],
[ 51.877743 , -0.4116338],
[ 51.877743 , -0.4116338]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.