简体   繁体   English

计算一行熊猫中最频繁的值,并用最频繁的值创建一列

[英]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.我尝试对转置的列进行转置和循环以获取 value_counts,但无法获得正确的结果。 Any help is highly appreciated.任何帮助都受到高度赞赏。

Use DataFrame.mode with select first column by positions with DataFrame.iloc :使用DataFrame.mode和按位置选择第一列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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM