【问题标题】:rename column based on conditional根据条件重命名列
【发布时间】:2021-04-23 02:53:11
【问题描述】:

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

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)

【问题讨论】:

    标签: python pandas conditional-statements rename


    【解决方案1】:

    问题出在这里:

    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
    

    【讨论】:

      【解决方案2】:

      替换你的代码行:

      dtcol2 = str(dtcol)
      

      与:

      dtcol2 = dtcol[0]
      

      这应该有效。目前,dtcol 是一个包含一个元素的列表:['Date']
      或者您可以通过以下方式简化操作:

      df.columns = [re.sub(r'^Date$', 'Activity Date', col) for col in df.columns]
      

      替换你所拥有的:

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

      注意:

      • 你需要“重新导入”
      • 假设您确定要搜索“日期”的字符串,这就是我使用r'^Date$' 搜索模式的原因

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-10-25
        • 2017-08-15
        • 2019-09-30
        • 1970-01-01
        • 2019-09-15
        • 2019-07-12
        • 2019-06-11
        • 2013-09-06
        相关资源
        最近更新 更多