0

Suppose I have a pandas data frame df with three columns and each column contains string values of either "a" or "b"

Col1 Col2 Col3
 a     b    a
 b     b    a
 a     a    a
 b     a    a
 b     b    b
 a     a    b

I want to count the number of times "a" and "b" appear in each row. How is this computed?

Ch3steR
  • 20,090
  • 4
  • 28
  • 58

1 Answers1

0

We can use pd.value_counts with df.apply

df.apply(pd.value_counts)

   Col1  Col2  Col3
a     3     3     4
b     3     3     2

In case, you want apply values_counts over axis 1 then use:

df.apply(pd.value_counts, axis=1)#.fillna(0) incase you want to eliminate NaNs

     a    b
0  2.0  1.0
1  1.0  2.0
2  3.0  NaN
3  2.0  1.0
4  NaN  3.0
5  2.0  1.0
Ch3steR
  • 20,090
  • 4
  • 28
  • 58
  • But, they say count in in each **row** – AziMez Nov 12 '21 at 10:36
  • @AziMez The linked answer solved what OP is looking for. This answer does exactly the same as the answers linked in the dupe. But I get point OP has to clarify what the expected output is since, row and column are often confused. – Ch3steR Nov 12 '21 at 10:52
  • 1
    If you mean **row** as in over axis 1 then `df.apply(pd.value_counts, axis=1)` should do it. @AziMez I'll edit my answer appropriately once OP clarifies or will delete incase they don't. – Ch3steR Nov 12 '21 at 10:55
  • *Thank you* for your clarification. Your response is ** very useful**. You can just EDIT it with this one: **df.apply(pd.value_counts, axis=1)** in the case of row. Since the question is already closed. – AziMez Nov 12 '21 at 11:01
  • 1
    @AziMez Yes, I edited that into my answer. Thank you. – Ch3steR Nov 12 '21 at 11:05