简体   繁体   中英

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:

A B (FYI)
apple orange ("couple 1")
tomato carrot ("couple 2")
banana kiwi ("couple 3")
orange apple ("couple 1" new occurence)
tomato carrot ("couple 2" new occurence)
salad eggplant ("couple 4")

I want to replace every new occurence of a same "couple" by à 0 (zero), like that:

A B (FYI)
apple orange ("couple 1")
tomato carrot ("couple 2")
banana kiwi ("couple 3")
0 0
0 0
salad eggplant ("couple 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")
0 0 ("couple 2")
0 0 ("couple 3")
0 0 ("couple 1" new occurence)
0 0 ("couple 2" new occurence)
0 0 ("couple 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. Same thing with item_2 and item_b . Perhaps your second loop should be range(n1 + 1, stop_row) ? Don't worry if n1 + 1 goes larger than 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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