Count instances of strings in multiple columns python

  • A+
Category:Languages

I have the following simple data frame

import pandas as pd df = pd.DataFrame({'column_a': ['a', 'b', 'c', 'd', 'e'],                    'column_b': ['b', 'x', 'y', 'c', 'z']})         column_a column_b 0        a        b 1        b        x 2        c        y 3        d        c 4        e        z 

I'm looking to display the strings which occur in both columns:

result = ("b", "c") 

Thanks

 


intersection

This generalizes over any number of columns.

set.intersection(*map(set, map(df.get, df)))  {'b', 'c'} 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: