Replace every value in pandas.DataFrame row with the count of that value

Viewed 42

I would like to replace the values in my pd.DataFrame, df with counts of the value in row.

import pandas as pd

df = pd.DataFrame({
  'foo': [3,3,1,1,1,2],
  'bar': [4,4,1,3,3,3]
}).transpose()
0 1 2 3 4 5
foo 3 3 1 1 1 2
bar 4 4 1 3 3 3

I would expect to see:

0 1 2 3 4 5
foo 2 2 3 3 3 1
bar 2 2 1 3 3 3

Unable to determine a solution using .apply().

What is the most sensible way of achieving the above?

1 Answers

One way using pandas.Series.value_counts with map:

df.apply(lambda x: x.map(x.value_counts()), axis=1)

Output:

     0  1  2  3  4  5
foo  2  2  3  3  3  1
bar  2  2  1  3  3  3
Related