gpt4 book ai didi

python - 在Python中将嵌套数组转换为pandas数据框

转载 作者:太空宇宙 更新时间:2023-11-03 16:04:31 27 4
gpt4 key购买 nike

我正在尝试将数组中包含的多个字典转换为 pandas 数据帧。字典保存如下:

[[{u'category': u'anti-social-behaviour',u'location': {u'latitude': u'52.309886',
u'longitude': u'0.496902'},u'month': u'2015-01'},{u'category': u'anti-social-behaviour',u'location': {u'latitude': u'52.306209',
u'longitude': u'0.490475'},u'month': u'2015-02'}]]

我正在尝试将数据格式化为以下格式:

     Category      Latitude   Longitude
0 anti-social 524498.597 175181.644
1 anti-social 524498.597 175181.644
2 anti-social 524498.597 175181.644
. ... ...
. ... ...
. ... ...

我尝试使用以下代码将数据强制放入数据框中,但它不会产生预期的输出。

for i in crimes:
for x in i:
print pd.DataFrame([x['category'], x['location']['latitude'], x['location']['longitude']])

我对 Python 非常陌生,因此任何帮助我构建此数据框的链接/提示将不胜感激!

最佳答案

您的方向是正确的,但是您正在为每一行创建一个新的数据框,并且没有提供正确的。以下代码片段应该有效:

import pandas as pd
import numpy as np

crimes = [[{u'category': u'anti-social-behaviour',u'location': {u'latitude': u'52.309886',
u'longitude': u'0.496902'},u'month': u'2015-01'},{u'category': u'anti-social-behaviour',u'location': {u'latitude': u'52.306209',
u'longitude': u'0.490475'},u'month': u'2015-02'}]]

# format into a flat list
formatted_crimes = [[x['category'], x['location']['latitude'], x['location']['longitude']] for i in crimes for x in i]

# now pass the formatted list to DataFrame and label the columns
df = pd.DataFrame(formatted_crimes, columns=['Category', 'Latitude', 'Longitude'])

结果是:

                Category   Latitude Longitude
0 anti-social-behaviour 52.309886 0.496902
1 anti-social-behaviour 52.306209 0.490475

关于python - 在Python中将嵌套数组转换为pandas数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39981740/

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