【问题标题】:Python Pandas nested MongoDBPython Pandas 嵌套 MongoDB
【发布时间】:2017-10-19 08:29:38
【问题描述】:

我尝试将嵌套的 mongodb 结果读取到 pandas 数据框中。

数据如下所示。

{
"_id" : ObjectId("5911b9cebb56c016794d45a4"),
"crawlat" : "2017-05-09 14:45",
"traffic" : [ 
    {
        "timestamp" : "1494338401",
        "organic" : 53
    }, 
    {
        "timestamp" : "1494342001",
        "organic" : 64
    }, 
    {
        "timestamp" : "1494345601",
        "organic" : 74
    }, 
    {
        "timestamp" : "1494349201",
        "organic" : 78
    }, 
    {
        "timestamp" : "1494352801",
        "organic" : 80
    }, 
    {
        "timestamp" : "1494356401",
        "organic" : 88
    }, 
    {
        "timestamp" : "1494360001",
        "organic" : 91
    }, 
    {
        "timestamp" : "1494363601",
        "organic" : 92
    }, 
    {
        "timestamp" : "1494367201",
        "organic" : 94
    }
]

}

流量数组包含每个结果的 48 个条目。

我只对按数组顺序排列的“有机”值感兴趣。

我从

开始
con = pymongo.MongoClient(['...:27017'])
collsitemap = con.sitemap.newssitemap
sitemapsdata = collsitemap.find({'traffic':{'$size':48}})

我使用 json_normalize 和

做了一些清理工作
dfsitemap = dfsitemap['traffic'].apply(pd.Series)

现在结果是这样的

但我需要一张只有有机值的表格。我该如何清理这个?

【问题讨论】:

  • 你的数据框中的两个维度是什么?

标签: python json mongodb pandas dataframe


【解决方案1】:

您可以使用from_records 构造函数创建数据框,它允许您指定要包含或排除的列:

pd.DataFrame.from_records(sitemapsdata['traffic'], exclude=['timestamp'])

给出:

【讨论】:

  • 好的,谢谢,我收到一个错误:TypeError: Argument 'rows' has wrong type (expected list, got Series) Traffic 是一个数组,如上所示。
  • 抱歉,这是一个可变错字。 from_records 的参数是一个字典列表(在您的情况下是 traffic 的值)。我已经更新了答案。
  • 现在我得到:TypeError: index 'traffic' cannot be applied to Cursor instances 查找将返回多行。
猜你喜欢
  • 1970-01-01
  • 2019-01-12
  • 2018-09-24
  • 2016-06-25
  • 2018-08-01
  • 2019-04-24
  • 1970-01-01
  • 2021-12-11
  • 2014-10-29
相关资源
最近更新 更多