1

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 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.