Saqib Ali
Saqib Ali

Reputation: 4428

Count occurances of a specific value in columns of list of list in python

I have a list as following:

[[1,0,1,3],
 [2,0,1,3],
 [2,3,0,2]]

I would like a count of appearance of 3 in each 3 as a list: ((0,0),(1,1),(2,0),(3,2))

What is the best to do this? Do I need to transpose and then use list comprehension?

Upvotes: 0

Views: 43

Answers (4)

Toni Homedes i Saun
Toni Homedes i Saun

Reputation: 716

Took some time. I'm a bit rusty with comprehensions. Thanks for a nice exercise.

m = [[1, 0, 1, 3], 
     [2, 0, 1, 3], 
     [2, 3, 0, 2]]

result = list([x, list(m[y][x] for y in range(3)).count(3)] for x in range(4))

print(result)

Upvotes: 1

Rafael Valero
Rafael Valero

Reputation: 2816

Using dataframes

import numpy as np
import pandas as pd


df = pd.DataFrame([[1,0,1,3],
 [2,0,1,3],
 [2,3,0,2]])

print((df==3).sum().sum())
3

There are 3 elements equals to 3.

Upvotes: 1

karthik r
karthik r

Reputation: 1071

Will this work?

from collections import Counter
counter = Counter()
[counter.update(x) for x in ip_]
print(tuple(counter.items()))

Upvotes: -2

Andrej Kesely
Andrej Kesely

Reputation: 195438

You don't need to transpose, just keep a helper dictionary with counters:

m = [[1, 0, 1, 3], [2, 0, 1, 3], [2, 3, 0, 2]]

counters = {}

for j in range(len(m)):
    for i in range(len(m[j])):
        counters.setdefault(i, 0)
        counters[i] += m[j][i] == 3

print(tuple(counters.items()))

Prints:

((0, 0), (1, 1), (2, 0), (3, 2))

Upvotes: 1

Related Questions