【问题标题】:How do I block a Keyerror in Python from reoccurring or create exception to handle it?如何阻止 Python 中的 Keyerror 再次发生或创建异常来处理它?
【发布时间】:2020-06-03 19:32:12
【问题描述】:

我是 Python 新手并使用 API,

我的代码如下:

import pandas as pd
import json
from pandas.io.json import json_normalize
import datetime

threedaysago = datetime.date.fromordinal(datetime.date.today().toordinal()-3).strftime("%F")
import http.client

conn = http.client.HTTPSConnection("api.sendgrid.com")
payload = "{}"

keys = {
#    "CF" : "SG.UdhzjmjYR**.-",
}
df = []  # Create new Dataframe

for name, value in keys.items():
    headers = { 'authorization': "Bearer " + value }

    conn.request("GET", "/v3/categories/stats/sums?aggregated_by=&start_date={d}&end_date={d}".format(d=threedaysago), payload, headers)

    res = conn.getresponse()
    data = res.read()
    print(data.decode("utf-8"))

    d = json.loads(data.decode("utf-8"))
    c=d['stats']
#    row = d['stats'][0]['name']
    # Add Brand to data row here with 'name'
    df.append(c)  # Load data row into df
#1    
df = pd.DataFrame(df[0])
df_new = df[['name']]
df_new.rename(columns={'name':'Category'}, inplace=True)
df_metric =pd.DataFrame(list(df['metrics'].values))
sendgrid = pd.concat([df_new, df_metric], axis=1, sort=False)
sendgrid.set_index('Category', inplace = True)
sendgrid.insert(0, 'Date', threedaysago)
sendgrid.insert(1,'BrandId',99)
sendgrid.rename(columns={
                       'blocks':'Blocks',
                       'bounce_drops' : 'BounceDrops',
                       'bounces': 'Bounces',
                       'clicks':'Clicks',
                       'deferred':'Deferred',
                       'delivered':'Delivered',
                       'invalid_emails': 'InvalidEmails',
                       'opens':'Opens',
                       'processed':'Processed',
                       'requests':'Requests',
                       'spam_report_drops' : 'SpamReportDrops',
                       'spam_reports' : 'SpamReports',
                       'unique_clicks' : 'UniqueClicks',
                       'unique_opens' : 'UniqueOpens',
                       'unsubscribe_drops' : 'UnsubscribeDrops',
                       'unsubscribes': 'Unsubscribes'
                       }, 
                 inplace=True)

但是,当我运行它时,我收到一个错误:

KeyError: "None of [Index(['name'], dtype='object')] are in the [columns]"

我知道发生这种情况的原因是因为三天前没有可用的统计数据:

{"date":"2020-02-16","stats":[]}

但是如何在我的代码中处理这些异常,因为这将作为每日报告运行,如果不处理此错误,它将中断。

【问题讨论】:

    标签: api dataframe exception error-handling


    【解决方案1】:

    抱歉回复晚了。

    KeyError: "None of [Index(['name'], dtype='object')] are in the [columns]" 表示您的数据框中没有名为name 的列。

    但是,您认为发生错误是因为"stats" : []。这也不是真的。如果任何索引为空,则错误应为ValueError: arrays must all be same length

    我已经重新创建了这个问题,我会告诉你如何解决这个问题。

    • 重新创建KeyError: "None of [Index(['name'], dtype='object')] are in the [columns]"
    import pandas as pd
    
    df = [{'A': [1,4,5], 'B': [4,5,6], 'C':['a','b','c']}]
    df = pd.DataFrame(df[0])
    df = df[['D']]
    
    print(df)
    

    输出-:

    KeyError: "None of [Index(['D'], dtype='object')] are in the [columns]"
    

    解决方案 -: 您可以看到数据框中没有名为“D”的列。因此,请重新检查您的列


    • 添加“D”看看会发生什么
    import pandas as pd
    
    df = [{'A': [1,4,5], 'B': [4,5,6], 'C':['a','b','c'], 'D': []}]
    df = pd.DataFrame(df[0])
    df = df[['D']]
    
    print(df)
    

    输出-:

    ValueError: arrays must all be same length
    

    解决方案-:“D”列需要填充与“A”、“B”和“C”相同的数据计数


    • 克服这两个问题
    import pandas as pd
    
    df = [{'A': [1,4,5], 'B': [4,5,6], 'C':['a','b','c'], 'D':[]}]
    
    df = pd.DataFrame.from_dict(df[0], orient='index')
    df.transpose()
    
    print(df)
    

    输出-:

          0     1     2
    A     1     4     5
    B     4     5     6
    C     a     b     c
    D  None  None  None
    

    您可以看到列现在表示为行。您可以使用loc 选择每一行列。

    import pandas as pd
    
    df = [{'A': [1,4,5], 'B': [4,5,6], 'C':['a','b','c'], 'D':[]}]
    
    df = pd.DataFrame.from_dict(df[0], orient='index')
    df.transpose()
    
    df = df.loc[['A']] # uses loc
    
    print(df)
    

    输出-:

       0  1  2
    A  1  4  5
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-08
      • 1970-01-01
      • 2012-11-16
      • 2018-07-09
      • 1970-01-01
      • 2010-10-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多