imack
imack

Reputation: 15

countif (with multiple column range) in python

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.

Upvotes: 1

Views: 155

Answers (1)

Vianpyro
Vianpyro

Reputation: 75

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

Upvotes: 1

Related Questions