【问题标题】:Find majority elements in a dataframe (PANDAS)在数据框中查找多数元素 (PANDAS)
【发布时间】:2022-11-18 00:12:07
【问题描述】:

我需要根据各列中的 (int64) 元素构建多数表决 (3/5) 作为新列 (Voting)

     Column1  Column2 Column3 Column4 Column5
0   0   0   6   1   0
1   4   4   6   4   0
2   4   2   2   2   2
3   4   4   4   4   4
4   0   0   0   2   4
5   6   6   6   6   6
6   3   3   3   3   5
7   0   6   6   0   4
8   3   3   3   3   4
9   2   2   4   2   2

我的预期结果是这样的:

     Column1  Column2 Column3 Column4 Column5 Voting
0   0   0   6   1   0       0
1   4   4   6   4   0       4      
2   4   2   2   2   2       2
3   4   4   4   4   4       4
4   0   0   0   2   4       0
5   6   6   6   6   6       6
6   3   3   3   3   5       3
7   0   6   6   0   4      -1
8   3   3   3   3   4       3
9   2   2   4   3   3      -1

where -1 is printed when we have pair number of elements.

Thanks a lot. 

【问题讨论】:

    标签: pandas voting


    【解决方案1】:

    试试,pd.Series.mode

    def f(x):
        result = x.mode()
        return result[0] if len(result) == 1 else -1
    
    df['vote'] = df.T.apply(f)
    print(df)
    

    输出:

       Column1  Column2  Column3  Column4  Column5  vote
    0        0        0        6        1        0     0
    1        4        4        6        4        0     4
    2        4        2        2        2        2     2
    3        4        4        4        4        4     4
    4        0        0        0        2        4     0
    5        6        6        6        6        6     6
    6        3        3        3        3        5     3
    7        0        6        6        0        4    -1
    8        3        3        3        3        4     3
    9        2        2        4        2        2     2
    

    【讨论】:

      猜你喜欢
      • 2022-06-29
      • 2019-01-26
      • 2017-01-31
      • 2021-12-20
      • 2021-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多