专栏名称: Dance with GenAI
关于生成式人工智能AIGC的一切
目录
相关文章推荐
BetterRead  ·  瞧,这个人讲信仰 ·  12 小时前  
BetterRead  ·  怎样用AI做规划? ·  昨天  
每日英语  ·  中国文化 | 打树花(Dashuhua) ·  昨天  
51好读  ›  专栏  ›  Dance with GenAI

AI办公自动化:Excel中批量智能合并单元格内容

Dance with GenAI  · 公众号  ·  · 2024-07-25 06:05

主要观点总结

文章介绍了一个使用Python脚本合并Excel表格中相同公司名称的对应产品和算法的任务。脚本读取指定Excel文件,根据“主体名称”列的内容合并“算法名称”和“应用产品”列的内容,并将结果保存至新的Excel文件中。

关键观点总结

关键观点1: 任务背景

将Excel表格中属于同一公司的产品和算法根据公司名称进行合并。

关键观点2: 具体步骤

1. 读取指定的Excel文件。2. 读取第4列“主体名称”中的内容。3. 识别内容一致的单元格,并获取其所在行的第2列“算法名称”和第5列“应用产品”。4. 将这些内容合并,并保存到新的Excel文件中。

关键观点3: 使用的工具和方法

使用Python的pandas库读取和写入Excel文件,使用iterrows()方法遍历表格,使用concat方法合并数据。

关键观点4: 注意事项

每一步都要输出信息到屏幕上,以便跟踪进度。另外,新版本的pandas库已经弃用了append方法,可以使用concat方法来替代。

关键观点5: 运行结果

在VSCode中运行程序成功合并单元格,并将结果保存至新的Excel文件中。


正文

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):

# Create a new DataFrame to store the merged data

merged_df = pd.DataFrame(columns=df.columns)

# Iterate through the DataFrame based on the column to check

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:

# Merge the rows and add to the new DataFrame

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)

# Handle the last group

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)







请到「今天看啥」查看全文