Excel表格中第4列“主体名称”是公司名称,第5列是公司的产品,现在要把一个公司的所有产品放在一起,就是根据第4列的公司名称来合并第5列的单元格。
Deepseek中输入提示词:
写一个Python脚本,完成合并单元格的任务,具体步骤如下:
读取Excel文件:"D:\360AI浏览器下载\境内深度合成服务算法备案清单20240718.xlsx"
读取第4列“主体名称”中所有单元格的内容;
如果某些单元格的内容一致,就将单元格所在行的第2列“算法名称”和第5列“应用产品”进行合并;
合并后的单元格内容保存到同一个文件夹中的新excel文件中:hebing.xlsx
注意:每一步都要输出信息到屏幕上
pandas库在较新的版本中已经弃用了append方法,可以使用concat方法来替代
源代码:
import pandas as pd
def merge_cells(df, column_to_check, columns_to_merge):
merged_df = pd.DataFrame(columns=df.columns)
current_value = None
rows_to_merge = []
for index, row in df.iterrows():
if current_value is None or row[column_to_check] != current_value:
if rows_to_merge:
merged_row = rows_to_merge[0].copy()
for col in columns_to_merge:
merged_row[col] = ', '.join(set(row[col] for row in rows_to_merge))
merged_df = pd.concat([merged_df, merged_row.to_frame().T], ignore_index=True)
rows_to_merge = []
current_value = row[column_to_check]
rows_to_merge.append(row)
if rows_to_merge:
merged_row = rows_to_merge[0].copy()
for col in columns_to_merge:
merged_row[col] = ', '.join(set(row[col] for row in rows_to_merge))
merged_df = pd.concat([merged_df, merged_row.to_frame().T], ignore_index=True)
return merged_df
def main():
input_file = r'D:\360AI浏览器下载\境内深度合成服务算法备案清单20240718.xlsx'
output_file = r'D:\360AI浏览器下载\hebing.xlsx'
print(f"Reading Excel file: {input_file}")
df = pd.read_excel(input_file)
column_to_check = '主体名称'
columns_to_merge = ['算法名称', '应用产品']
print(f"Merging cells based on column: {column_to_check}")
merged_df = merge_cells(df, column_to_check, columns_to_merge)
print(f"Saving merged data to new Excel file: {output_file}")
merged_df.to_excel(output_file, index=False)
if __name__ == "__main__":
main()
在vscode中运行程序,成功合并。