Pandas:如何找到每行中最常出现的值?

2024-04-24 15:10:29 发布

您现在位置:Python中文网/ 问答频道 /正文

如何找到数据帧中每一行的最频繁值? 例如:

In [14]: df
Out[14]:
   a  b  c
0  2  3  3
1  1  1  2
2  7  7  8

返回: [3,1,7]


Tags: 数据indfout
1条回答
网友
1楼 · 发布于 2024-04-24 15:10:29

尝试.mode()方法:

In [88]: df
Out[88]:
   a  b  c
0  2  3  3
1  1  1  2
2  7  7  8

In [89]: df.mode(axis=1)
Out[89]:
   0
0  3
1  1
2  7

来自文档:

Gets the mode(s) of each element along the axis selected. Adds a row for each mode per label, fills in gaps with nan.

Note that there could be multiple values returned for the selected axis (when more than one item share the maximum frequency), which is the reason why a dataframe is returned. If you want to impute missing values with the mode in a dataframe df, you can just do this: df.fillna(df.mode().iloc[0])

相关问题 更多 >