How to find all ocurrences of an element in all columns of a DataFrame?

I’m trying to find all ocurrences of an element in a DataFrame. I’m using str.count and str.contains but I can’t get a function to get the sum of all the elements.

df.apply(lambda row: row.astype(str).str.count('word'), axis=1)
A   B   C   D   E   F   G   H   I   J
1   0   1   0   1   0   0   0   1   0
0   0   0   0   0   0   0   0   0   0
0   0   0   0   0   0   0   0   0   0

# Something like this
df.apply(lambda row: sum(row.astype(str).str.count('word')), axis=1)
0    4
1    0
2    0

# Expected output:
4

Answer

You can just do stack , then do not need apply

df.stack().astype(str).str.count('word').sum()

Leave a Reply

Your email address will not be published. Required fields are marked *