【问题标题】:Python Error Logging to Check for Duplicate Rows and Duplicate Columns用于检查重复行和重复列的 Python 错误日志记录
【发布时间】:2019-10-02 16:53:28
【问题描述】:

以下代码读取现有的 MS Excel 电子表格,创建列图,然后将结果导出到另一个 Excel 电子表格。工作表和相关列实际上要大得多,但为了保持上下文简单,我已将地图中的列数配对。

您会注意到,在此过程中,我创建了 2 个 NULL 列并删除了所有重复的行。我正在努力尝试正确的 Try: except: 语句,该语句将验证我没有用创建的 NULL 列覆盖现有列,并验证没有重复的行。我知道我不是,但出于审计目的需要错误日志报告。以下是代码的简单模型,据我所知。我对异常处理还是很陌生,希望能得到您的帮助。提前致谢。

from datetime import datetime
import logging

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s]  %(message)s",
    handlers=[logging.StreamHandler()])

os.chdir(r'M:\Loans')

col_map = {'Loan #' : 'LoanNo',
           'Last Name' : 'LastName',
           'Purchase Price' : 'PurchasePrice',
           'Loan Amt' : 'LoanAmt',
           'Property Address' : 'PropertyAddress',
           'City' : 'City',
           'State' : 'State',
           'Zip Code' : 'ZipCode',
           'Interest Rate' : 'InterestRate',
           'UPBCurrent' : 'UPBCurrent',               
           'NextDueDateAtPurchase' : 'NextDueDateAtPurchase',
           'CurrentAdvanceRate': 'CurrentAdvanceRate',
           'Comments' : 'Comments',
           'CurrentAdvanceAmount': 'CurrentAdvanceAmount',
           'SecondRoundCurrentAdvanceRate' : 'SecRoundCurrentAdvRate', 
           'SecondRoundCurrentAvanceAmount' : 'SecRoundCurrentAdvAmount', 
           }

for f in os.listdir():

    logging.info('Reading in file {}'.format(f))

df=pd.read_excel('M:\Loans\Loan Blotter XYZ OLD.xlsx')

df['UPBCurrent'] = None
df['NextDueDateAtPurchase'] = None

df = df[col_map.keys()]
df.drop_duplicates(inplace=True)
df.columns = [col_map[col] for col in df.columns]
df['Channel'] = 'Whole Loans'
df['DateCreated'] = datetime.today().date()
df.to_excel(r'M:\Err Log.xlsx', index=False)

【问题讨论】:

    标签: python excel pandas exception


    【解决方案1】:

    检查您不会覆盖现有的列:

    null_cols = ['UPBCurrent', 'UPBCurrent']
    for null_col in null_cols:
        if null_col in df.columns:
            logging.error("{} will be overwritten.".format(null_col))
        else:
            logging.info("Adding null column {}.".format(null_col))
            df[null_col] = None
    

    检查删除重复项是否有效:

    try:
        df.drop_duplicates(inplace=True)
    except:
        logging.error("Failed to drop duplicate rows.")
    

    【讨论】:

    • 工作完美。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 2015-05-28
    • 1970-01-01
    • 1970-01-01
    • 2022-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多