【问题标题】:How to get the mode of a column in pandas where there are few of the same mode values pandas如何在熊猫中获得相同模式值很少的熊猫列的模式
【发布时间】:2019-12-31 06:09:45
【问题描述】:

我有一个数据框,我想获取特定列的模式。 我正在使用:

freq_mode = df.mode()['my_col'][0]

但是我得到了错误:

ValueError: ('The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()', 'occurred at index my_col')

我猜这是因为我几乎没有相同的模式。 我需要任何模式,没关系。我如何使用any() 来获取任何存在的模式?

【问题讨论】:

  • 什么返回print(df.mode()['my_col'])

标签: pandas dataframe mode any


【解决方案1】:

对我来说,您的代码可以很好地处理示例数据。

如有必要,请从mode 中选择系列的第一个值:

freq_mode = df['my_col'].mode().iat[0]

【讨论】:

    【解决方案2】:

    我们可以看到一列

    df=pd.DataFrame({"A":[14,4,5,4,1,5], 
                     "B":[5,2,54,3,2,7], 
                     "C":[20,20,7,3,8,7], 
                     "train_label":[7,7,6,6,6,7]}) 
    X=df['train_label'].mode()
    print(X)
    

    数据帧

        A   B   C  train_label
    0  14   5  20            7
    1   4   2  20            7
    2   5  54   7            6
    3   4   3   3            6
    4   1   2   8            6
    5   5   7   7            7
    

    输出

    0    6
    1    7
    dtype: int64
    

    【讨论】:

      猜你喜欢
      • 2023-01-23
      • 2017-08-04
      • 2021-03-10
      • 1970-01-01
      • 2020-07-21
      • 2021-12-24
      • 2016-03-11
      • 1970-01-01
      • 2016-02-29
      相关资源
      最近更新 更多