Pratik
Pratik

Reputation: 53

Count the most frequent values in a row pandas and make a column with that most frequent value

I have a data frame like this below:

     a  b  c
0    3  3  3
1    3  3  3
2    3  3  3
3    3  3  3
4    2  3  2
5    3  3  3
6    1  2  1
7    2  3  2
8    0  0  0
9    0  1  0

I want to count frequency of each row and add a column result containing the max frequency like this below:

     a  b  c result
0    3  3  3  3
1    3  3  3  3
2    3  3  3  3
3    3  3  3  3
4    2  3  2  2
5    3  3  3  3
6    1  2  1  1
7    2  3  2  2
8    0  0  0  0
9    0  1  0  0

I tries to do transpose and looping through the transposed columns to get the value_counts but could not got the right result. Any help is highly appreciated.

Upvotes: 2

Views: 1067

Answers (1)

jezrael
jezrael

Reputation: 862511

Use DataFrame.mode with select first column by positions with DataFrame.iloc:

df['result'] = df.mode(axis=1).iloc[:, 0]
print (df)
   a  b  c  result
0  3  3  3       3
1  3  3  3       3
2  3  3  3       3
3  3  3  3       3
4  2  3  2       2
5  3  3  3       3
6  1  2  1       1
7  2  3  2       2
8  0  0  0       0
9  0  1  0       0

Upvotes: 4

Related Questions