简体   繁体   English

python 和 openpyxl:如何替换 excel 表上新出现的日期?

[英]python and openpyxl : how to replace new occurence of a date on excel sheet?

I have an excel sheet containing data on two columns (A & B) like that:我有一个 excel 表,其中包含两列(A 和 B)上的数据,如下所示:

A一个 B (FYI) (供参考)
apple苹果 orange ("couple 1") (“情侣 1”)
tomato番茄 carrot萝卜 ("couple 2") (“情侣 2”)
banana香蕉 kiwi猕猴桃 ("couple 3") (“情侣 3”)
orange apple苹果 ("couple 1" new occurence) (“情侣1”新出现)
tomato番茄 carrot萝卜 ("couple 2" new occurence) (《情侣2》新登场)
salad沙拉 eggplant茄子 ("couple 4") (“情侣 4”)

I want to replace every new occurence of a same "couple" by à 0 (zero), like that:我想用 à 0(零)替换同一“夫妇”的每一个新出现,就像这样:

A一个 B (FYI) (供参考)
apple苹果 orange ("couple 1") (“情侣 1”)
tomato番茄 carrot萝卜 ("couple 2") (“情侣 2”)
banana香蕉 kiwi猕猴桃 ("couple 3") (“情侣 3”)
0 0 0 0
0 0 0 0
salad沙拉 eggplant茄子 ("couple 4") (“情侣 4”)

i taught that a simple code like this one would be ok:我教过这样一个简单的代码就可以了:


import openpyxl
from openpyxl import *
import numpy
from numpy import *

wb = load_workbook("Desktop/programme/wb.xlsx")

ws = wb["Sheet"]

stop_row = ws.max_row + 1

for n1 in range(1,stop_row) :

    for n2 in range(2,stop_row) :

        item_a = ws.cell(row=n1, column=1).value
        item_b = ws.cell(row=n1, column=2).value

        item_1 = ws.cell(row=n2, column=1).value
        item_2 = ws.cell(row=n2, column=2).value

        if (item_a == item_1 and item_b == item_2) or (item_a == item_2 and item_b == item_1) :

            ws.cell(row=n2, column=1).value = 0
            ws.cell(row=n2, column=2).value = 0

But what i get is:但我得到的是:

A一个 B (FYI) (供参考)
apple苹果 orange ("couple 1") (“情侣 1”)
0 0 0 0 ("couple 2") (“情侣 2”)
0 0 0 0 ("couple 3") (“情侣 3”)
0 0 0 0 ("couple 1" new occurence) (“情侣1”新出现)
0 0 0 0 ("couple 2" new occurence) (《情侣2》新登场)
0 0 0 0 ("couple 4") (“情侣 4”)

any idea why?知道为什么吗?

Thanks谢谢

First iteration, n1 = 1 and n2 = 1. The values item_1 and item_a will be the same with that setup because they're pointing to the same cell.第一次迭代,n1 = 1 和 n2 = 1。值item_1item_a将与该设置相同,因为它们指向同一个单元格。 Same thing with item_2 and item_b .item_2item_b相同。 Perhaps your second loop should be range(n1 + 1, stop_row) ?也许你的第二个循环应该是range(n1 + 1, stop_row) Don't worry if n1 + 1 goes larger than stop_row;如果 n1 + 1 大于 stop_row,请不要担心; it just won't count anything instead of looping around.它只是不会计算任何东西而不是循环。

Also, be aware if you do this, you'll have to start n1 from 0, otherwise the first row will never be considered.另外,请注意,如果这样做,则必须从 0 开始 n1,否则将永远不会考虑第一行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM