Home > Software design >  Returning count of 0 if value doesn't exist Pandas DataFrame
Returning count of 0 if value doesn't exist Pandas DataFrame

Time:09-27

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?

CodePudding user response:

Series support .get(), so:

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

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

  • Related