Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Value counts within col

How could I calculate the value counts within a string col?

df col
0 fruit["apple"], colour["green", "yellow" ] 
1 colour["yellow"] 
2 colour["brown"] 

Expected Output

fruit  1
colour 3

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use Series.str.extractall with substrings joined by | for regex or:

s = df['col'].str.extractall('(fruit|colour)')[0].value_counts()
print (s)
colour    3
fruit     1
Name: 0, dtype: int64

Or get words before [ for more dynamic solution:

s = df['col'].str.extractall(r'(\w+)\[')[0].value_counts()
print (s)
colour    3
fruit     1
dtype: int64
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading