【发布时间】:2019-04-22 09:31:25
【问题描述】:
具有 2 列的数据框:old_path 和 new_path。数据框可以包含数百行。
脚本遍历文件列表。
对于列表中的每个文件,检查其文件夹路径的任何部分是否与 old_path 列中的值匹配。如果匹配,则将文件匹配的old_path 替换为对应的new_path 值。
我通过for index, row in df.iterrows(): 或for row in df.itertuples(): 实现了这一点,但我认为应该有一种更有效的方法来做到这一点,而不必使用第二个for 循环。
感谢任何帮助。下面的示例使用df.iterrows()
import pandas as pd
import os
df = pd.read_csv('path_lookup.csv')
# df:
# old_path new_path
# 0 F:\Business\Budget & Forecasting M:\Business\Finance\Forecast
# 1 F:\Business\Treasury Shared M:\Business\Finance\Treasury
# 2 C:\Temp C:\NewTemp
excel_link_analysis_list = [
{'excel_filename': 'C:\\Temp\\12345\\Distribution Adjusted Claim.xlsx',
'file_read': 'OK'},
{'excel_filename': 'C:\\Temp\\SubFolder\\cost estimates.xlsx',
'file_read': 'OK'}
]
for i in excel_link_analysis_list:
for index, row in df.iterrows():
if row['old_path'].lower() in i['excel_filename'].lower():
dest_path_and_file = i['excel_filename'].lower().replace(row['old_path'].lower(),
row['new_path'].lower())
print(dest_path_and_file)
打印:
c:\newtemp\12345\distributionadjusted claim.xlsx
c:\newtemp\子文件夹\成本估算.xlsx
【问题讨论】:
标签: python pandas loops for-loop filepath