[英]Replace missing values in excel worksheet using openpyxl module
I'm trying to replace cells in my Excel worksheet that contains hyphen “-“ with the average value between the above lying cell and the below lying cell. 我正在尝试用上面的说谎者单元格和下面的说谎者单元格之间的平均值替换包含连字符“-”的Excel工作表中的单元格。 I'll been trying to do this by looping through each row in column 3
我将尝试通过遍历第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)
is this just to easy to do or is it not possible with openpyxl? 这仅仅是为了容易做到还是用openpyxl无法做到?
cheers// Smiffo 干杯// Smiffo
The reason values are not replaced is that you use i
to check if its equal to -
. 不替换值的原因是您使用
i
来检查其是否等于-
。 i is an index, not the value of a cell. 我是一个索引,而不是一个单元格的值。 Also to calculate the mean, you are using indices, not the values of top and below cells.
同样,为了计算平均值,您使用的是索引,而不是顶部和底部单元格的值。
So you could solve this in following way: 因此,您可以通过以下方式解决此问题:
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
Not that this may require tweaking, as it does not accout for cases where tob and bottom rows are -
, not numbers, or just empty cells. 并不是说这可能需要进行调整,因为对于tob和bottom行是
-
,不是数字或只是空单元格的情况,这并不适用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.