Find frequency of given character at every position in list of lists in Python

Lets consider a scenario where you have a list which is made of lists as its elements. We are interested in finding the frequency of one character at different positions of the inner lists. Below example will clarify the requirement.

Consider a list of lists given below.

listA = [['a', 'a', 'b'],
['a', 'c', 'b'],
['c', 'a', 'b'],
['c', 'a', 'a']]

In the abobe list we have elements which are lists with 3 elements. If I consider the first inner list tit has a,a,b at positions 0,1,2. Similarly for the 3rd list it is c,a,b at 0,1,2. Considering all the inner lists we can say the frequency a at position 0 is 2, and at position 1 is 3 and at position 2 it is 1.

The programs below aim to find such values for any element in the list of lists.

Uisng pandas

The pandas library is extensively used for data manipulation by creating dataframes. So we create a dataframe and loop through it with a where clause to find if the value ‘a’ is present in each position in the data frame.

Example

Live Demo

import pandas as pd

# Given list of lists
listA = [['a', 'a', 'b'],
['a', 'c', 'b'],
['c', 'a', 'b'],
['c', 'a', 'a']]

# using pandas
df = pd.DataFrame(listA)
res = df.where(df == 'a', 0).where(df != 'a', 1)

# Result
print("Occurrence of 'a' at 0,1 and 2 position\n", res.sum())

Output

Running the above code gives us the following result −

Occurrence of 'a' at 0,1 and 2 position
0 2.0
1 3.0
2 1.0

With zip

We can use a for loop to loop through each position in the sublist in the list and applying zip function to th entire list of lists.

Example

Live Demo

# Given list of lists
listA = [['a', 'a', 'b'],
['a', 'c', 'b'],
['c', 'a', 'b'],
['c', 'a', 'a']]

res = [elem.count('a') for elem in zip(*listA)]
# Result
print("Occurrence of 'a' at 0,1 and 2 position\n", res)

Output

Running the above code gives us the following result −

Occurrence of 'a' at 0,1 and 2 position
[2, 3, 1]

Updated on: 05-May-2020

151 Views