【问题标题】:Calculate mode on a dataframe without sorting the result在数据帧上计算模式而不对结果进行排序
【发布时间】:2018-08-28 13:26:57
【问题描述】:

我有一个这样的数据框:

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),但这似乎会按行顺序打乱值的顺序,所以我并不总是得到输出中第一列的值。 H2>

【问题讨论】:

  • 我已经更新了问题。棘手的部分不见了。我不认为它是重复的。
  • “模式不存在”是指平局?
  • @BallpointBen 是的。

标签: python pandas dataframe mode


【解决方案1】:

无排序方法

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])
    

【讨论】:

  • 为什么不只是df.mode(axis=1)[0]
  • 请检查问题中的注释。抱歉,我最初应该更新这个。
  • @cᴏʟᴅsᴘᴇᴇᴅ 您的回答在某些情况下会失败。我已经用新行更新了 df 。请检查。
  • @ManishSaraswat 您好,如果这是您需要的,您可以考虑接受吗?
  • @cᴏʟᴅsᴘᴇᴇᴅ 终于解决了问题。我会接受你的回答,因为你没有放弃。
【解决方案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.])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-05
    • 2020-11-02
    • 1970-01-01
    相关资源
    最近更新 更多