我正在尝试将包含连字符“ - ”的Excel工作表中的单元格替换为上述单元格与下方单元格之间的平均值。我一直试图通过循环第3列中的每一行
来做到这一点 import math
from openpyxl import load_workbook
import openpyxl
d_filename="Snow.xlsx"
wb = load_workbook(d_filename)
sheet_ranges=wb["PIT 1"]'
def interpolatrion_of_empty_cell():
for i in range(7,31):
if i =="-":
sheet_ranges.cell(row = i, column = 3).value = mean(i-1,i+1)
else:
sheet_ranges.cell(row = i, column = 3).value
wb.save(filename = d_filename)
这只是为了容易做到,还是用openpyxl不可能?
//欢呼声 Smiffo
答案 0 :(得分:2)
未更换原因值是您使用i
检查其是否等于-
。我是一个索引,而不是一个单元格的值。另外,要计算平均值,您使用的是索引,而不是顶部和底部单元格的值。
所以你可以通过以下方式解决这个问题:
def interpolatrion_of_empty_cell():
for i in range(7,31):
cell_value = sheet_ranges.cell(row=i, column=3).value
if cell_value == "-":
top_value = sheet_ranges.cell(row=i+1, column=3).value
bottom_value = sheet_ranges.cell(row=i - 1, column=3).value
sheet_ranges.cell(row=i, column=3).value = (float(top_value) + float(bottom_value))/2
不是这可能需要调整,因为它不适用于tob和底行是-
,而不是数字或只是空单元格的情况。