How to count elements in a column that are integers?
Here is what I came up with:
import re
pd.Series(["a","2","z","123","a","oops"]).apply(lambda x: x and re.match(r"^\d+$",x) and 1).sum()
==> 2.0
and
def isint (x):
try:
int(x)
return 1
except ValueError:
return 0
pd.Series(["a","2","z","123","a","oops"]).apply(isint).sum()
==> 2
Obviously, the second approach is better (returns to int, easily generalizes to other types - dates, float& c), but I wonder if there is an even better way that would not require me to write my own function.
source
share