Returning count of 0 if value doesn't exist Pandas DataFrame

Question:

I am trying to set 2 variables as counts of a specific value in a column.

I have one variable here:

missing_gmt = missing_records._merge.value_counts().Missing_in_GMTLib

That correctly returns: 44

I also have another variable here:

missing_nsl = missing_records._merge.value_counts().Missing_in_NSL

Which should return 0 (no records exist) but instead is throwing:

AttributeError: 'Series' object has no attribute 'Missing_in_NSL'

How can I bypass this error so it returns 0 instead?

Asked By: JD2775

||

Answers:

Series support .get(), so:

.value_counts().get('Missing_in_NSL', 0)

Docs: Series.get() (though the examples there are for df.get())

Answered By: wjandrea
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.