use*_*161 5 python json dataframe python-3.x pandas
我正在尝试对从 Google 时间轴获得的我自己的位置数据进行一些描述。但是当试图获取一些可行的数据时,将其从 JSON 文件转换为 DataFrame。它提出了一些我想得到一些答案的问题,因为在尝试将 JSON 文件转换为 DataFrame 时,我觉得我将以一种低效的方式进行。
描述我的 JSON 是什么样的。它是一个 3 层深的 JSON,大约有 450 万行。JSON 的一个小例子:
"locations" : [
{
"timestampMs" : "1489591483",
"latitudeE7" : -21.61909,
"longitudeE7" : 121.65283,
"accuracy" : 23,
"velocity" : 18,
"heading" : 182,
"altitude" : 55,
"activity" : [ {
"timestampMs" : "1489591507",
"activity" : [ {
"type" : "IN_VEHICLE",
"confidence" : 49
}, {
"type" : "UNKNOWN",
"confidence" : 17
}, {
"type" : "ON_BICYCLE",
"confidence" : 15
}, {
"type" : "ON_FOOT",
"confidence" : 9
}, {
"type" : "STILL",
"confidence" : 9
}, {
"type" : "WALKING",
"confidence" : 9
} ]
} ]
},
...
]
Run Code Online (Sandbox Code Playgroud)
要将其转换为 DataFrame,我想将这 3 个级别展平到 0 个级别。我已经看到了 json_normalize 与 .apply 或 .append 结合的一些实现,但因此您仍然需要知道值的键,我宁愿看到它更通用(所以不知道键)。它还需要手动迭代这些值。现在我想知道的是:“是否有一种方法可以在不使用应用或附加的情况下自动将 JSON 展平到 0 级?” 如果没有这样的方法,那么将 JSON 扁平化并将其转换为 DataFrame 的首选方法是什么?
编辑:添加了一个关于 DataFrame 应该是什么样子的示例和一个更好的 JSON 示例。
要给出 DataFrame 应该是什么样子的一个小例子,请参见下图:

为了包含一个更好的 JSON 示例,我在下面包含了一个 Pastebin URL: tiny location history sample
使用json_normalize,指定record_path和meta_path。
df = pd.io.json.json_normalize(d, ['locations', 'activity', 'activity'],
['locations', ['locations', 'activity', 'timestampMs']])
df = df.drop('locations', 1).add_prefix('activity.')
v = pd.DataFrame(df['locations'].tolist()).drop('activity', 1)
pd.concat([df, v], 1)
activity.confidence activity.type activity.locations.activity.timestampMs \
0 49 IN_VEHICLE 1489591507
1 17 UNKNOWN 1489591507
2 15 ON_BICYCLE 1489591507
3 9 ON_FOOT 1489591507
4 9 STILL 1489591507
5 9 WALKING 1489591507
accuracy altitude heading latitudeE7 longitudeE7 timestampMs velocity
0 23 55 182 -21.61909 121.65283 1489591483 18
1 23 55 182 -21.61909 121.65283 1489591483 18
2 23 55 182 -21.61909 121.65283 1489591483 18
3 23 55 182 -21.61909 121.65283 1489591483 18
4 23 55 182 -21.61909 121.65283 1489591483 18
5 23 55 182 -21.61909 121.65283 1489591483 18
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2086 次 |
| 最近记录: |