Pandas如何将某个列表中的数值追加到excel指定列的数据后面
这个excel有很多个列每列长度不一,我需要依次对其中数据进行更新,每次更新数据都存储在一个列表中,我该怎么把该列表中数据更新到excel
部分代码如下
# 复制连续三个数据之后的所有值
copied_data = source_column_data[start_index + 3:]
#print('a',copied_data)
#读取目标文件
target_data_df = pd.read_excel(all_data_file, sheet_name = target_sheet_name)
#print(target_data_df)
if target_data_df is not None:
# 找到目标列的索引
target_column_index = target_data_df.columns.get_loc(target_column_name)
#print('a',target_column_index)
# 将复制的数据转换为DataFrame,并指定列名
copied_data_df = pd.DataFrame({target_column_name: copied_data})
# 将copied_data_df中的数据追加到target_data_df中
target_data_df = pd.concat([target_data_df.iloc[:, :target_column_index + 1], copied_data_df, target_data_df.iloc[:, target_column_index + 1:]], axis=1)
# 修改显示的最大列数和行数,设置为None表示不限制
pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None)
print(target_data_df)
# 将目标列的数据更新到目标Excel文件的指定工作表中
with pd.ExcelWriter(all_data_file, engine='openpyxl') as writer:
writer.book = openpyxl.load_workbook(all_data_file)
writer.sheets = dict((ws.title, ws) for ws in writer.book.worksheets)
merged_df.to_excel(writer, sheet_name=target_sheet_name, index=False)
print(f"在源Excel文件 '{source_excel}' 中找到连续三个数据,已复制{len(copied_data)}个数据到目标Excel文件的工作表 '{target_sheet_name}' 的指定列的数据之后。")
else:
print(f"在源Excel文件 '{source_excel}' 中未找到连续三个数据。")