首页 > 解决方案 > 根据条件重命名列

问题描述

如果列名包含一个字符串,我正在尝试重命名列,它会创建一个所有列名的列表,如果“日期”在其中一个名称中,那么它会对其进行重命名。一切正常,但重命名部分没有显示错误,但随后我打印列名,原始名称仍显示:

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")
    dtcol = [col for col in df.columns if "Date" in col]
    dtcol2 = str(dtcol)
    df.rename(columns={dtcol2: "Activity Date"}, inplace=True)
    cols = df.columns
    if "SOURCE" in cols:
        if df.SOURCE.map(lambda x: len(x)).max() == 0:
            df['File'] = f
            df_xlsx = pd.concat([df, df_xlsx], ignore_index=True)
            df_xlsx = df_xlsx[["Email","SOURCE","File"]]
        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)

标签: pythonpandasconditional-statementsrename

解决方案


问题在这里:

dtcol = [col for col in df.columns if "Date" in col]
dtcol2 = str(dtcol)
df.rename(columns={dtcol2: "Activity Date"}, inplace=True)
cols = df.columns

dtcol是一个列表,即使它是单个元素,当您使用时,str(dtcol)您正在创建一个字符串,例如'["Date 1"]',该字符串不存在于df. 另一方面,该函数rename()在未找到任何值时不会生成错误,而是根本不做任何事情并继续执行脚本,这就是为什么您永远看不到任何更改的原因。您需要迭代dtcol

dtcol = [col for col in df.columns if "Date" in col]
for ex in dtcol:
   df.rename(columns={ex: "Activity Date"}, inplace=True)
cols = df.columns

推荐阅读