Skip to content
Advertisement

What’s a pythonic way (native function in pandas) to count occurrences of a certain value within cases (SPSS COUNT equivalent)?

I need to count occurrences of a certain value (let’s assume it’s 3) in a range of columns per each case. To do so I wrote a script as below:

JavaScript

First print is:

JavaScript

Second:

JavaScript

Even though it works fine I am pretty sure there is a more pythonic way to do so. By ‘pythonic’ I mean using native, concise pandas feature and no looping through columns/rows. For example, in SPSS there is a simple count command so regarding this objsourcedf this line would be:

JavaScript

Sadly, as a beginner in Python and pandas I couldn’t find anything so I’m asking you if there’s a more simple way to get occurences?

Advertisement

Answer

I hope this qualifies at being “Pythonic”:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement