# Change values of a particular column to value_count()

Suppose i have the following data set. I need to replace the value of a particular column by the value_count(). I saw few posts where it is done for the entire data set. I need to do it for a particular column.

data = pd.DataFrame({'Item 1': ['apple', 'potato', 'cheese', 'banana', 'cheese', 'banana', 'cheese', 'potato', 'egg'],
'Item 2': [1,5,2,7,8,4,9,0,3],
'Item 3': ['a','b','a','c','d','c','e','e','e']})


How do i replace the values of column 'Item 1' by the value_counts()?

I tried the following code.

data.apply(lambda x: x.map(x.value_counts()))


But this is applying to whole data. I need to do it for one column.

The resulting value should be of the form -

'Cheese':3

'Potato':2

• Are you trying to change, for example, all 'cheese'  entries to 3? Please post code of what you have tried. May 31 '19 at 11:38
• @Edmund I have edited the post. Yes, i am trying to change 'cheese' to 3, 'potato' to 2 etc. May 31 '19 at 11:42

Try this:

# Do value_count outside of loop to avoid doing it multiple times
vc_item1 = data['Item 1'].value_counts()

data['Item 1'].apply(lambda x: vc_item1[x])


But if understand your comment correctly you want both key and value in each cell:

vc = data['Item 1'].value_counts()

data['Item 1'].apply(lambda x: str(x) + ':' + str(vc[(x)]))

• above code works fine. I need to display data in the form cheese:3, potato:2 etc. Like key:value pair May 31 '19 at 11:59
• Sounds like you just want the value count itself. Maybe my edit will help. May 31 '19 at 12:07
• I don't need data in dict form. The value stored in each row should be of key:value pair May 31 '19 at 12:33
• Hmm, are you saying you want both key and value inside each cell? Should they be together as a string? It is hard to tell what you are trying to achieve. May 31 '19 at 12:53
• Yes key:value inside each cell. For example, cheese:3. Cell has key cheese, and value is the frequency of cheese(3). May 31 '19 at 13:01