Home > database >  countif (with multiple column range) in python
countif (with multiple column range) in python

Time:12-08

I'm trying to do this 2 simple excel functions in python but is very hard! I'm a newbie in python...

example

Can anyone help me? Thanks in advance, imack.

CodePudding user response:

This is the closest I could do for now, it is not perfect but maybe you will find a way to improve it :)

table = [
    ["a", "b"],
    ["b", "c"],
    ["c", "d"],
    ["b", "c"],
    ["c", "a"],
    ["a", "c"],
    ["c", "a"],
    ["c", "b"],
    ["a", "c"],
    ["c", "b"],
]

def countif(table, condition):
    count = 0
    for row in table:
        for col in row:
            if condition(col):
                count  = 1
    return count

for index, element in enumerate(table):
    print(*element, countif(table[:index], lambda x: x == table[index][0]))

Result:

a b 0
b c 1
c d 1
b c 2
c a 3
a c 2
c a 5
c b 6
a c 4
c b 8
  • Related