1

I am populating a new column in a pandas DataFrame with a value count of each number in a list.

test_scores_series['Label_{}'.format(choices[i])] = test_scores_series.apply(lambda y: y.value_counts() , axis=1)[choices[i]]

Now, when choices[i] = 10 or any value that does not appear in the current column, I get a KeyError for that value!

As I understand, value_counts() only returns counts as long as they are not zero. How do I bypass the KeyError and impute a zero if the value is not found?

This is not a duplicate of any questions related to dictionary. It's a pandas specific question. Apparently in an older version, pandas would return the keys with zero counts too and it doesn't happen anymore.

boltthrower
  • 1,230
  • 3
  • 12
  • 29

1 Answers1

1

I think what you want is

test_scores_series.apply(lambda y: y.value_counts() , axis=1).get(choices[i], 0)
Alex L
  • 1,114
  • 8
  • 11