簡體   English   中英

使用pandas在python中合並兩個字典列表

[英]Merge two lists of dicts in python using pandas

我有兩個命令列表:一個包含每月數據,另一個包含季度數據,如下所示:

monthly = [
{
    "name": "Boston",
    "month": "2015-May",  
    "total_monthly": 2
}, 
{
    "name": "Boston",
    "month": "2015-June",  
    "total_monthly": 8
}, 
{
    "name": "Chicago",
    "month": "2015-May",  
    "total_monthly": 10
},
{
    "name": "Chicago",
    "month": "2015-June",  
    "total_monthly": 13
}
]

quarterly =[
{
    "name": "Boston",
    "quarter": "2015-Q1",  
    "total_quarterly": 23
}, 
{
    "name": "Boston",
    "quarter": "2015-Q2",  
    "total_quarterly": 24
}, 
{
    "name": "Chicago",
    "quarter": "2015-Q1",  
    "total_quarterly": 40
},
{
    "name": "Chicago",
    "quarter": "2015-Q2",  
    "total_quarterly": 32
}
]

按照慣例,我可以遍歷列表並根據通用名稱合並它們。 但是,如何使用Pandas實現合並數據,如下所示?

merged = [
{
  "name": "Boston",
  "trend_monthly" : [
    {
      "month": "2015-May",  
      "total_monthly": 2
    }, 
    {
      "month": "2015-June",  
      "total_monthly": 8
    },
  ],  
  "trend_quarterly" : [
    {
      "quarter": "2015-Q1",  
      "total_quarterly": 23
    }, 
    {
      "quarter": "2015-Q2",  
      "total_quarterly": 24
    },
  ]
},
{
  "name": "Chicago",
  "trend_monthly" : [
    {
      "month": "2015-May",  
      "total_monthly": 10
    }, 
    {
      "month": "2015-June",  
      "total_monthly": 13
    },
  ],  
  "trend_quarterly" : [
    {
      "quarter": "2015-Q1",  
      "total_quarterly": 40
    }, 
    {
      "quarter": "2015-Q2",  
      "total_quarterly": 32
    },
  ]
}]          

您必須執行以下操作:

import pandas as pd

df_monthly = pd.DataFrame(monthly)
df_quarterly = pd.DataFrame(quarterly)

df = pd.concat([df_monthly, df_quarterly])

# This part does not group correctly, please edit for your needs
result = []
dict_monthly = dict(list(df[df.month.notnull()][['name',
                                                  'month',
                                                  'total_monthly']
                                                ].groupby(by='name')))

dict_quarterly = dict(list(df[df.quarter.notnull()][['name',
                                                  'quarter',
                                                  'total_quarterly']
                                                ].groupby(by='name')))
result.append(dict_monthly)
result.append(dict_quarterly)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM