3

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'
KHAN irfan
  • 421
  • 1
  • 7
  • 16

1 Answers1

3

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)
Simon Larsson
  • 4,173
  • 1
  • 14
  • 29