这可能是一个常见问题,但我有一个使用 os 和 pandas 包的 Python 3.11.5 项目。
我需要读取和写入 Excel 文件。
目标是读取 9 个源文件。对于每个源文件,我想获取源文件的列标题下方的数据。然后,我想将该数据迁移到目标文件的相应列。目标文件的第一行只是分析人员的信息。顺便说一句,信息只是描述下一行中的标题。因此,第二行有标题。数据从目标 Excel 文件的第三行开始。目标 Excel 文件最初没有数据。
对于每对源列标题“File NameX”和“File CategoryX”,我想获取其数据。
这里,X 是 1 到 26 之间的数字。标题名称中恰好有 26 对包含“文件名”和“文件类别”的标头,所以这就是为什么 1 <= X <= 26. After the python script gets data from the Xth pair, I want to populate the Xth destination file's corresponding columns with that data. Destination files are named so that the Xth destination file is called 'dest (X).xlsx'. So, X is the number between 1 and 26 and X from 'dest (X).xlsx' that also equals X from 'File NameX' and 'File CategoryX'. 'File NameX' from source corresponds to 'ITEM_DOCUMENT' in destination and 'File CategoryX' from source corresponds to 'ITEM_DOCUMENT_TYPE' in destination.
问题:我的程序似乎覆盖目标文件,而不是简单地将数据从源附加到目标文件标题行的下方。我说“似乎覆盖”是因为虽然目标文件的标题被保留,但格式不同(在某些地方使用黑色粗体字体而不是红色粗体字体),第一行不再有分析人员的标题信息,并且宽度不同,也。
如何简单追加?我的代码主要功能的一部分:
for i, (file_name_col, file_category_col) in \
enumerate(zip(file_name_cols, file_category_cols), start=1):
dest_file = os.path.join(dest_folder, f"dest ({i}).xlsx")
# Check Column Existence:
file_name_col = f'File Name{i}'
file_category_col = f'File Category{i}'
if file_name_col in source_data.columns and \
file_category_col in source_data.columns:
# Create destination DataFrame with specified headers if the file doesn't exist
if not os.path.isfile(dest_file):
dest_columns = ['PART_NUMBER', 'LANGUAGE_CODE', 'MANUFACTURER_NAME',
'BRAND_NAME', 'ITEM_DOCUMENT', 'ITEM_DOCUMENT_TYPE']
dest_data = pd.DataFrame(columns=dest_columns)
dest_data.to_excel(dest_file, index=False)
# Read the existing destination data or
# create an empty DataFrame if the file doesn't exist
dest_data = pd.read_excel(dest_file, header=1) \
if os.path.isfile(dest_file) else pd.DataFrame()
dest_columns = ['PART_NUMBER', 'LANGUAGE_CODE', 'MANUFACTURER_NAME',
'BRAND_NAME', 'ITEM_DOCUMENT', 'ITEM_DOCUMENT_TYPE']
# Ensure that the destination file has the required columns
for col in dest_columns:
if col not in dest_data.columns:
dest_data[col] = ''
new_data = source_data[['PART_NUMBER', 'LANGUAGE_CODE', \
'MANUFACTURER_NAME', 'BRAND_NAME']].copy()
new_data['ITEM_DOCUMENT'] = source_data[file_name_col].copy()
new_data['ITEM_DOCUMENT_TYPE'] = \
new_data['ITEM_DOCUMENT'].apply(determine_document_type)
# Append new data to the existing destination file
dest_data = pd.concat([dest_data, new_data], ignore_index=True)
# Write the combined data to the destination file
dest_data.to_excel(dest_file, index=False, sheet_name='Sheet1', engine='openpyxl')
else:
# Handle the case where the columns don't exist
raise ValueError(f"Columns '{file_name_col}' \
and/or '{file_category_col}' do not exist in source_data.")
我尝试过通过 ChatGPT 运行它,但它已经没有想法了,而且总是忘记我已经尝试过的事情。请帮帮我。如果需要更多信息,我很乐意提供。我将在周末监视这篇文章——这是一个工作项目。任务自动化。尝试进行概念验证。谢谢,保重。
这确实是莫肯的答案,但是——被替换了
dest_data = pd.concat([dest_data, new_data], ignore_index=True)
# Write the combined data to the destination file
dest_data.to_excel(dest_file, index=False, sheet_name='Sheet1', engine='openpyxl')
与
# Use ExcelWriter to append data to an existing file
with pd.ExcelWriter(dest_file, engine='openpyxl', mode='a', if_sheet_exists='overlay') as writer:
# Write the new data to the destination file
new_data.to_excel(writer, index=False, sheet_name='Sheet1', startrow=2, header=None)
并且获得了附加到 Excel 工作表的所需结果,而没有覆盖标题。