2
$\begingroup$

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

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

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)]))
$\endgroup$
5
  • $\begingroup$ above code works fine. I need to display data in the form cheese:3, potato:2 etc. Like key:value pair $\endgroup$
    – Harshith
    May 31 '19 at 11:59
  • $\begingroup$ Sounds like you just want the value count itself. Maybe my edit will help. $\endgroup$ May 31 '19 at 12:07
  • $\begingroup$ I don't need data in dict form. The value stored in each row should be of key:value pair $\endgroup$
    – Harshith
    May 31 '19 at 12:33
  • $\begingroup$ 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. $\endgroup$ May 31 '19 at 12:53
  • $\begingroup$ Yes key:value inside each cell. For example, cheese:3. Cell has key cheese, and value is the frequency of cheese(3). $\endgroup$
    – Harshith
    May 31 '19 at 13:01

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.