gpt4 book ai didi

python - 如何分解(或弹出)JSON 数组两次

转载 作者:行者123 更新时间:2023-12-01 09:18:25 25 4
gpt4 key购买 nike

我正在尝试使用 pop 弹出包含 JSON 数组的 MongoDB 文档,通常如果 MongoDB 文档只是 JSON,它会很好地工作,在 JSON 数组中它会产生太多列,所以我无法轻松弹出非 JSON 格式。对于更详细的问题,我在下面给出解释

这是我的数据

Id locations
1 [{'timestamp': 2018-05-28 15:00:00, 'lat': 0.0..
2 [{'timestamp': 2018-05-28 15:00:00, 'lat': 0.0..

我尝试弹出的内容

df = df.join(pd.DataFrame(df.pop('locations').values.tolist(), index=df.index))

输出为

Id   0                              1                            ...      136
1 {'timestamp': 2018-05-28... {'timestamp': 2018-05-28... {'timestamp': 2018-05-28...
2 {'timestamp': 2018-05-28... {'timestamp': 2018-05-28... None

我期望的输出是

Id   0                             
1 {'timestamp': 2018-05-28...
1. {'timestamp': 2018-05-28...
...
{'timestamp': 2018-05-28...
2 {'timestamp': 2018-05-28...
...
{'timestamp': 2018-05-28...

所以,我可以再次弹出

最佳答案

我认为需要融化:

df2 = df.join(pd.DataFrame(df.pop('locations').values.tolist(), index=df.index)).melt('Id')

或者stack :

s = (pd.DataFrame(df.pop('locations').values.tolist(), index=df.index)
.stack()
.reset_index(level=1, drop=True))

df2 = df.join(s.rename('new'))

或者具有重复 Id 值和展平嵌套 list 的 numpy 解决方案:

df2 = pd.DataFrame({
"Id": np.repeat(df.Id.values, df.locations.str.len()),
"new": list(chain.from_iterable(df.locations))})
print (df2)
Id new
0 1 {'timestamp': '2018-05-28 15:00:00', 'lat': 0.0}
1 1 {'timestamp': '2018-05-28 16:00:00', 'lat': 0.0}
2 2 {'timestamp': '2018-05-28 10:00:00', 'lat': 0.0}
3 2 {'timestamp': '2018-05-28 17:00:00', 'lat': 0.0}
4 2 {'timestamp': '2018-05-28 18:00:00', 'lat': 0.0}

设置:

df = pd.DataFrame({'Id':[1,2], 
'locations':[[{'timestamp': '2018-05-28 15:00:00', 'lat': 0.0}, {'timestamp': '2018-05-28 16:00:00', 'lat': 0.0}],
[{'timestamp': '2018-05-28 10:00:00', 'lat': 0.0}, {'timestamp': '2018-05-28 17:00:00', 'lat': 0.0}, {'timestamp': '2018-05-28 18:00:00', 'lat': 0.0}]]})
print (df)


Id locations
0 1 [{'timestamp': '2018-05-28 15:00:00', 'lat': 0...
1 2 [{'timestamp': '2018-05-28 10:00:00', 'lat': 0...

关于python - 如何分解(或弹出)JSON 数组两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51019323/

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