python - 根据条件重命名列
问题描述
如果列名包含一个字符串,我正在尝试重命名列,它会创建一个所有列名的列表,如果“日期”在其中一个名称中,那么它会对其进行重命名。一切正常,但重命名部分没有显示错误,但随后我打印列名,原始名称仍显示:
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)
解决方案
问题在这里:
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
推荐阅读
- javascript - 遍历一个集合,其中键是 ID,值是用户类
- ios - 捕获视频并通过 AVAssetWriter 保存
- c# - WPF。是否有用于在 WPF 中选择字体的对话框窗口?
- java - JTabbedPane 更改侦听器以从文件中读取
- amazon-web-services - 如何在 Fn::Sub 中正确执行正则表达式
- mysql - 访问几何字段的纬度和经度
- sql-server - 测试 (90%) 和控制 (10%) 在零售商级别和 SQL 中的细分级别划分。怎么做?
- node.js - SetTimeout 和串行端口事件 - 代码执行顺序
- c++ - QPlainTextEdit 在即将删除选择时通知/挂钩
- reactjs - Reactjs setState 异步