【问题标题】:How to convert nested dic of python coming in response using pandas.dataframe() function如何使用 pandas.dataframe() 函数转换嵌套的 Python 字典作为响应
【发布时间】:2019-06-08 06:14:27
【问题描述】:

我无法按照我的意愿转换输出:

x = {
     "urlCrawlErrorSample": [ 
         {
           "urlDetails": {
                           "containingSitemaps": ['asff','123'],
                           "linkedFromUrls": ['xcvxcvad','89767']
                          },
           "first_detected": "A String", 
           "pageUrl": "A String", 
           "responseCode": 42, 
           "last_crawled": "A String"
         }  
      ]
     }

我申请了什么:

df = 
pandas.DataFrame.from_dict(json_normalize(x['urlCrawlErrorSample']), orient='columns')

我得到了什么,输出:

df
  first_detected last_crawled   pageUrl  responseCode urlDetails.containingSitemaps urlDetails.linkedFromUrls
0       A String     A String  A String            42                   [asff, 123]         [xcvxcvad, 89767]

想要的输出:

 df
  first_detected last_crawled   pageUrl  responseCode urlDetails.containingSitemaps urlDetails.linkedFromUrls
0       A String     A String  A String            42                          asff                  xcvxcvad
1       A String     A String  A String            42                          123                      89767

【问题讨论】:

    标签: pandas dataframe python-3.5


    【解决方案1】:

    解决这个问题的一种方法

    x = {
     "urlCrawlErrorSample": [ 
         {
           "urlDetails": {
                           "containingSitemaps": ['asff','123'],
                           "linkedFromUrls": ['xcvxcvad','89767']
                          },
           "first_detected": "A String", 
           "pageUrl": "A String", 
           "responseCode": 42,       
     "last_crawled": "A String"
         }  
      ]
     }
    
    a = pd.DataFrame(x['urlCrawlErrorSample']*2)
    b = pd.DataFrame(x['urlCrawlErrorSample'][0]['urlDetails'])
    print( pd.concat([a,b], axis=1).drop('urlDetails', axis=1) )
    

    输出

      first_detected last_crawled   pageUrl  responseCode containingSitemaps  \
    0       A String     A String  A String            42               asff   
    1       A String     A String  A String            42                123   
    
      linkedFromUrls  
    0       xcvxcvad  
    1          89767  
    

    【讨论】:

      猜你喜欢
      • 2022-11-03
      • 2023-03-11
      • 1970-01-01
      • 2018-02-16
      • 1970-01-01
      • 2018-08-08
      • 2021-06-14
      • 2019-06-18
      • 1970-01-01
      相关资源
      最近更新 更多