【问题标题】:How to find if the most common value of a column appears more than X% times?如何查找列的最常见值是否出现超过 X% 次?
【发布时间】:2020-11-08 00:12:31
【问题描述】:

考虑以下数据框:

  ID   Column
0 500  2
1 500  2
2 500  2
3 500  2
4 500  2
5 500  4

我们如何查看 'Column' 的最常见值是否出现超过 X% 的次数?

我试过这样做:df.locate[df.groupby('ID')['Column'].count_values(normalize=True).max() > X],但我得到一个错误。

【问题讨论】:

    标签: pandas


    【解决方案1】:

    我认为您所拥有的已接近解决方案。我不太清楚,如果你想在整个列或每个组上计算这个,所以这里有一个解决方案。您可以更改变量at_least_this_proportion,以更改最小阈值:

    import pandas as pd
    from io import StringIO
    
    text = """
      ID   Column
    0 500  2
    1 500  2
    2 500  2
    3 500  2
    4 500  2
    5 500  4
    6 501  2
    7 501  2
    """
    
    df = pd.read_csv(StringIO(text), header=0, sep='\s+')
    
    # set minimum threshold
    at_least_this_proportion = 0.5
    

    按组计算:

    # find the value that occurs at least 50% within its group
    value_counts_per_group = df.groupby('ID')['Column'].value_counts(normalize=True)
    ids_that_meet_threshold = value_counts_per_group[value_counts_per_group > at_least_this_proportion].index.get_level_values(0)
    
    # get all rows for which the id meets the threshold
    df[df['ID'].isin(ids_that_meet_threshold)]
    

    【讨论】:

    • 我没有正确澄清。我想要第二个(即每组)。感谢您提供两者!但是,我希望输出是 ID 满足条件的所有行。在您给出的示例中,所有行都满足此条件。也就是说,即使是第 5 行 (500 4) 也会是 True 并因此返回。
    • 好的,改变解决方案:找到满足阈值的 id 并获取这些 id 的所有行
    猜你喜欢
    • 2022-01-05
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-27
    • 1970-01-01
    相关资源
    最近更新 更多