首页 > 解决方案 > 空列表条件

问题描述

我从读取 excel 文件的列中得到一个列表,我需要验证列是否在列表中,如果没有,则将其创建为空,但条件不起作用,我知道缺少“城市”这一事实所以我期待它被创建,但不是。

files = os.listdir(input_path)
files_xlsx = [f for f in files if f[-5:] == ".xlsx"]

df = pd.DataFrame()

for f in files_xlsx:
    wb = load_workbook(input_path + "\\" + f, read_only=True)
    if 'New Leads' in wb.sheetnames:
        df = pd.read_excel(input_path + "\\" + f, sheet_name="New Leads")
        colre = [col for col in df.columns if "Email" in col]
        for eo in colre:
            df.rename(columns={eo: eo.replace(' ','').replace('*','').replace('**','') for eo in colre}, inplace=True)
        dtcol = [col for col in df.columns if "FIRST NAME" in col.upper()]
        for ex in dtcol:
            df.rename(columns={ex: "First Name"}, inplace=True)
        dtcol = [col for col in df.columns if "LAST NAME" in col.upper()]
        for ex in dtcol:
            df.rename(columns={ex: "Last Name"}, inplace=True)

不工作的代码

        dtcol = [col for col in df.columns if "CITY" in col.upper()]
        for ex in dtcol:
            if len(dtcol)==0:
                df['City'] = NaN
            else:
                df.rename(columns={ex: "City"}, inplace=True)

不工作的代码结束

        dtcol = [col for col in df.columns if "COMPANY NAME" in col.upper()]
        for ex in dtcol:
            df.rename(columns={ex: "*** Company"}, inplace=True)
        if "SOURCE" in cols:
            df['Email'].replace('', np.nan, inplace=True)
            df.dropna(subset=['Email'], inplace=True)
            if df.dtypes['SOURCE'] != 'float':
                df.dropna(how = 'all')
                df['File'] = f
                if df.SOURCE.map(lambda x: len(x)).max() <= 10:
                    df = pd.merge(df, df_ac[["SOURCE", "Lead Source", "Lead Category"]], on="SOURCE", how='left')
                    del df['SOURCE']
                    df.rename(columns={"Lead Source": "SOURCE"}, inplace=True)
                else:
                    df.rename(columns={"SOURCE": "Lead Source"}, inplace=True)
                    df = pd.merge(df, df_ac[["Lead Source", "Lead Category"]], on="Lead Source", how='left')
                    df.rename(columns={"Lead Source": "SOURCE"}, inplace=True)
                df_xlsx = pd.concat([df, df_xlsx], ignore_index=True)
            else:
                df_ns = df_ns.append([f], ignore_index=True)
        else:
            df_ns = df_ns.append([f], ignore_index=True)
    else:
        df_ns = df_ns.append([f], ignore_index=True)

标签: pythonlistconditional-statements

解决方案


当你让 Python 遍历一个空列表时,它什么也不做,因为没有什么可以遍历的。所以放在if len(dtol)==0for循环里面什么都不做;如果列表为空,则永远不会对其进行评估,如果列表不为空,则将其评估为 false (这很浪费,因为必须在循环的每次迭代中对其进行评估,即使每次都相同)。你需要把它放在外面。

    dtcol = [col for col in df.columns if "CITY" in col.upper()]
    if dtcol:
        for ex in dtcol:
            df.rename(columns={ex: "City"}, inplace=True)
    else:
        df['City'] = NaN

推荐阅读