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

标签 python python-2.7

我正在尝试将数组中包含的多个字典转换为 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/

相关文章:

python - 找不到 _iconv 的 pyspatialite 符号

python - 我对字符串方法 .replace 感到困惑

python - 修补在另一个函数中导​​入的函数

python - Twisted:ReconnectingClientFactory 连接到不同的服务器

python - 在 Google App Engine 上使用 Mandrill/MailChimp 发送确认邮件

python - 我应该使用 brew 还是 pip 来安装 matplotlib?

python - 使用 python 连接到域以确定服务器是否在线

python - 如何在函数中定义参数。

python 列表索引越界

python - 来自外键的 Django 管理限制模型