3
$\begingroup$

I have a dataframe, I want to replace the values in one column by "other" if the value count of that value in that column is exactly 1

i        Food_group
0          Flake
1          Flake
2          Flake
3         Almond
4          Drink
5          Drink
6          Flake

I have tried,

data["food_group"] = data.food_group.apply(lambda x: "other" if x.value_counts()==1 else x)

I got error

AttributeError: 'str' object has no attribute 'value_counts'
$\endgroup$
3
$\begingroup$

It is easier if you store the value count separately to avoid redoing it inside the apply loop. You can do it like this:

food_count = data["food_group"].value_counts()
data["food_group"] = data["food_group"].apply(lambda x: "other" if food_count[x]==1 else x)
$\endgroup$
  • $\begingroup$ Have you tried the code? it does not work $\endgroup$ – KHAN irfan Apr 21 at 9:43
  • $\begingroup$ Test it now. :) Tried on another dataset and forgot to change back to "food_group" $\endgroup$ – Simon Larsson Apr 21 at 9:45
  • $\begingroup$ Tested it on your data now, so it should work. $\endgroup$ – Simon Larsson Apr 21 at 9:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.