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}' 中未找到连续三个数据。")
从你的描述和代码来看,你是在尝试将一个列表(copied_data)追加到一个已有的DataFrame的列后。你的代码中一部分应该已经成功实现这个功能,但是你可能混淆了“追加数据”和“插入新列”之间的差异。
如果你的目标是将列表中的数据追加到已存在的DataFrame列的末尾,你可能需要对你的代码进行一些修改。下面是一个修改后的代码示例:
# ...
# 你的其他代码
if target_data_df is not None:
# 找到目标列的索引
target_column_index = target_data_df.columns.get_loc(target_column_name)
# 你已经有一个名为'copied_data_df'的DataFrame,它包含了你希望追加到目标列末尾的数据。
# 可以直接将这些数据追加到目标列末尾
target_data_df[target_column_name] = target_data_df[target_column_name].append(copied_data_df, ignore_index=True)
# 修改显示的最大列数和行数,设置为None表示不限制
pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None)
print(target_data_df)
# ...
# 你的其他代码
这样,你的列表(已经转换为DataFrame)中的数据就会被追加到目标DataFrame列的末尾,而不是作为一个新列插入到DataFrame中。
然后你可以使用ExcelWriter将结果写入Excel文件。注意,这种写入方式会覆盖原文件中的数据,所以务必确保你已经保存原文件的备份。另外,你在写入Excel时引用了一个叫做merged_df
的变量,但在你给出的代码中并没有定义它,我在这里假设你实际上是想写入的是target_data_df
。如果我理解错了你的问题或需求,请提供更多的信息,我会很高兴再次为你提供帮助。
import pandas as pd
df = pd.read_excel('D:/py_project/datafenxi/scut.xls',sheet_name='savedrecs')
ji_he = {'name1','name2','name3',任意多个name}
这里的ji_he是提供的学院所有老师的姓名,与下面的要筛选的表格A做匹配,标记出A中一作为老师的论文。那剩下的未标记就是学生。