从下载的位置历史数据中使用熊猫创建数据帧



我从谷歌地图数据下载了位置历史json,并希望将所有可用内容放入pandas数据帧中。

df['locations'][5] yields the following:
{'timestampMs': '1540084102574',
'latitudeE7': 327160442,
'longitudeE7': -1171687098,
'accuracy': 17,
'altitude': -13,
'verticalAccuracy': 3,
'activity': [{'timestampMs': '1540083982124',
'activity': [{'type': 'STILL', 'confidence': 100}]}]}

我可以使用毫无问题地绘制时间戳、纬度和经度

df['lat'] = df['locations'].map(lambda x: x['latitudeE7'])/10.**7
df['long'] = df['locations'].map(lambda x: x['longitudeE7'])/10.**7 
df['ts_ms'] = df['locations'].map(lambda x: x['timestampMs']).astype(float)/1000

但由于返回"KeyError",因此无法实现高度或垂直精度

活动中还有一个嵌套结构。我该如何将这些映射到数据帧?

我已经尝试如下重现您的问题:

sample = {
'timestampMs': '1540084102574',
'latitudeE7': 327160442,
'longitudeE7': -1171687098,
'accuracy': 17,
'altitude': -13,
'verticalAccuracy': 3,
'activity': [{
'timestampMs': '1540083982124',
'activity': [{
'type': 'STILL',
'confidence': 100
}]
}]
}
# Creating an empty `DataFrame` of length one
df = pd.DataFrame([None],columns=['locations'])
# Passing your sample dictionary as its only value
df['locations'][0] = sample

现在,altituteverticalAccuracy对我来说都很好,因为它们都是外部字典中的keys

df['altitude'] = df['locations'].map(lambda x: x['altitude'])
df['verticalAccuracy'] = df['locations'].map(lambda x: x['verticalAccuracy'])

对于嵌套项,请注意activity是长度为1的list

type(sample.get('activity'))  # returns `list`
len(sample.get('activity'))  # returns 1

因此,您需要对列表的第一个(在本例中为零(项进行索引。该项将是Pythondictionary,需要通过括号表示法或更安全的.get()方法来访问。

df['timestampMs'] = df['locations'].map(lambda x: x['activity'][0].get('timestampMs'))

您可以将示例逻辑应用于嵌套在外部关键字中的内部activity字典关键字。

df['type'] = df['locations'].map(lambda x: x['activity'][0].get('activity')[0].get('type'))
df['confidence'] = df['locations'].map(lambda x: x['activity'][0].get('activity')[0].get('confidence'))

最新更新