计算数据帧的模式而不对结果进行排序

YOL*_*OLO 2 python mode dataframe pandas

我有一个像这样的数据框:

df = pd.DataFrame({'a1': [2,3,4,8,8], 'a2': [2,5,7,5,10], 'a3':[1,9,4,10,2]})

    a1  a2  a3
0   2   2   1
1   3   5   9
2   4   7   4
3   8   5   10
4   8   10  2
Run Code Online (Sandbox Code Playgroud)

输出应该是:

0  2 
1  3
2  4
3  8 
4  8
Run Code Online (Sandbox Code Playgroud)

该怎么做:我想按行计算众数,如果众数不存在,我想要 a1 (第一列)中的值。

例如:在第二行中(3,5,9),模式不存在,因此我进入3输出。

注意:我已经尝试过df.mode(axis=1),但这似乎会按行打乱值的序列,因此我并不总是获得输出中第一列的值。

cs9*_*s95 5

无排序方法

agg+ collections.Counter. 不对模式进行排序

from collections import Counter
df.agg(lambda x: Counter(x).most_common(1)[0][0], axis=1)

0    2
1    3
2    4
3    8
4    8
dtype: int64
Run Code Online (Sandbox Code Playgroud)

模式排序方法

  1. mode沿第一个轴使用,然后取先出现的值:

    df.mode(axis=1).iloc[:, 0]
    
    Run Code Online (Sandbox Code Playgroud)

    或者,

    df.mode(axis=1)[0] 
    
    Run Code Online (Sandbox Code Playgroud)

    0    2.0
    1    3.0
    2    4.0
    3    5.0
    4    2.0
    Name: 0, dtype: float64
    
    Run Code Online (Sandbox Code Playgroud)
  2. scipy.stats.mode

    from scipy.stats import mode
    np.array(mode(df, axis=1))[0].squeeze()
    array([2, 3, 4, 5, 2])
    
    Run Code Online (Sandbox Code Playgroud)