如何使用python读取excel文件的第四列,第六列,第八列,并分别计算出各列中'偏高' '正常' '偏低'的数量,生成列表,并填入excel

您所在的位置:网站首页 r中怎么读取excel文件 如何使用python读取excel文件的第四列,第六列,第八列,并分别计算出各列中'偏高' '正常' '偏低'的数量,生成列表,并填入excel

如何使用python读取excel文件的第四列,第六列,第八列,并分别计算出各列中'偏高' '正常' '偏低'的数量,生成列表,并填入excel

2023-06-10 22:00| 来源: 网络整理| 查看: 265

可以使用Python中的openpyxl库来读取和写入Excel文件,以下是一个基本的代码示例:

import openpyxl # 打开Excel文件 workbook = openpyxl.load_workbook('example.xlsx') # 选择指定的worksheet worksheet = workbook['Sheet1'] # 计算指定列中出现'偏高' '正常' '偏低'的数量 def count_occurrences(column_index): values = [cell.value for cell in worksheet.iter_cols(min_col=column_index, max_col=column_index)][1:] high_count = values.count('偏高') normal_count = values.count('正常') low_count = values.count('偏低') return [high_count, normal_count, low_count] # 分别计算第四列、第六列、第八列中出现'偏高' '正常' '偏低'的数量 column4_counts = count_occurrences(4) column6_counts = count_occurrences(6) column8_counts = count_occurrences(8) # 将计算结果放入一个列表 result = [column4_counts, column6_counts, column8_counts] # 创建一个新的worksheet,并填入计算结果 result_worksheet = workbook.create_sheet('Result') result_worksheet.append(['Column 4', 'Column 6', 'Column 8']) for row in result: result_worksheet.append(row) # 保存Excel文件 workbook.save('example.xlsx')

注意,在读取Excel文件时,iter_cols()函数返回一个列的所有单元格对象,使用[1:]切片剔除第一行表头。在写入Excel文件时,我们需要将计算结果放入一个列表,并使用append()函数写入到新的worksheet中。最后,我们保存这个Excel文件。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3