在不对结果进行排序的情况下计算数据帧的模式

Calculate mode on a dataframe without sorting the result

我有这样一个数据框:

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

输出应该是:

0  2 
1  3
2  4
3  8 
4  8

怎么办:我想按行计算模式,如果模式不存在,我想要 a1(第一列)的值。

例如:在第二行 (3,5,9) 中,模式不存在,所以我在输出中得到 3

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

No-Sort 方法

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

模式排序方法

  1. 沿第一个轴使用mode,然后取先到者:

    df.mode(axis=1).iloc[:, 0]
    

    或者,

    df.mode(axis=1)[0] 
    

    0    2.0
    1    3.0
    2    4.0
    3    5.0
    4    2.0
    Name: 0, dtype: float64
    
  2. scipy.stats.mode

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

另一种选择是使用 np.where:

mode = df.mode(axis=1)
np.where(mode.iloc[:,-1].isnull(),
    mode.iloc[:,0], # No tie, use the calculated mode 
    df.iloc[:,0]) # Tie, use the first column of the original df
# array([2., 3., 4., 8., 8.])