'count the number of strings in a 2-D pandas series [duplicate]

I am trying to count the number of characters in an uneven 2-D pandas series.

df = pd.DataFrame({ 'A' : [['a','b'],['a','c','f'],['a'], ['b','f']]}

I want to count the number of times each character is repeated.

any ideas?



Solution 1:[1]

You can use explode() and value_counts().

import pandas as pd

df = pd.DataFrame({ 'A' : [['a','b'],['a','c','f'],['a'], ['b','f']]})

df = df.explode("A")
print(df.value_counts())

Expected output:

A
a    3
b    2
f    2
c    1

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mushroomator