gpt4 book ai didi

python - 压平深度嵌套的 JSON 以获取 Dataframe 的最快且通用的方法是什么?

转载 作者:太空狗 更新时间:2023-10-30 02:54:04 27 4
gpt4 key购买 nike

我正在尝试对从我的 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
} ]
} ]
},
...
]

为了将其转换为 DataFrame,我想将这 3 个级别展平为 0 个级别。我已经看到一些将 json_normalize 与 .apply 或 .append 结合使用的实现,但因此您仍然需要知道值的键,我宁愿看到它更通用(所以不知道键)。它还需要手动迭代这些值。现在我想知道的是:“是否有一种方法可以在不使用应用或追加的情况下自动将 JSON 扁平化为 0 级?”如果没有这样的方法,将 JSON 扁平化并将其转换为 DataFrame 的首选方法是什么?


编辑:添加了一个 DataFrame 应该是什么样子的例子和一个更好的 JSON 例子。


举一个 DataFrame 应该是什么样子的小例子,见下图: An example of DataFrame

为了包含一个更好的 JSON 示例,我在下面包含了一个 Pastebin URL: tiny location history sample

最佳答案

使用json_normalize,指定record_pathmeta_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

关于python - 压平深度嵌套的 JSON 以获取 Dataframe 的最快且通用的方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47367665/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com