1

I have a list of lists in Python

[[0 0 0 ... 0 0 0]
[0 0 0 ... 0 0 0]
[0 0 0 ... 3 3 3]
[0 0 0 ... 4 4 4]
[1 2 1 ... 2 2 2]
[1 3 1 ... 3 3 3]
[1 4 1 ... 4 4 4]
[2 3 2 ... 3 3 3]
[2 4 2 ... 4 4 4]
[3 4 4 ... 4 4 4]]

I want to take the mode of each index and create a single list. For example for index zero, most common element is 0 so new list should have 0 for that index. What is the most efficient and best way to do it? I thought of converting them to numpy arrays and working on arrays but couldn't figure out.

2 Answers2

2

I assume you are referring to mode

You can use scipy for this -

data = np.random.randint(0,5,(100,9))
modes, counts = stats.mode(data, axis=1)

print('first row ->', data[0])
print('mode of first row ->', modes[0][0])
print('frequency ->', counts[0][0])
first row -> [0 0 1 2 1 2 4 1 1]
mode of first row -> 1
frequency -> 4
Akshay Sehgal
  • 18,741
  • 3
  • 21
  • 51
2

You could consider using statistics.mode in a list comprehension:

from statistics import mode

list_of_lists = [[0, 0, 0, 0, 0, 0],
                 [0, 0, 0, 0, 0, 0],
                 [0, 0, 0, 3, 3, 3],
                 [0, 0, 0, 4, 4, 4],
                 [1, 2, 1, 2, 2, 2],
                 [1, 3, 1, 3, 3, 3],
                 [1, 4, 1, 4, 4, 4],
                 [2, 3, 2, 3, 3, 3],
                 [2, 4, 2, 4, 4, 4],
                 [3, 4, 4, 4, 4, 4]]

mode_of_each_list = [mode(xs) for xs in list_of_lists]
print(mode_of_each_list)

Output:

[0, 0, 0, 0, 2, 3, 4, 3, 4, 4]
Sash Sinha
  • 18,743
  • 3
  • 23
  • 40