Pandas all() 但有阈值

问题描述 投票:0回答:1

假设我们有以下数据框和程序逻辑

import pandas as pd

df = pd.DataFrame({'A': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 'B': [4, 5, 6, 7, 8, 9, 10, 11, 12, 13]})


def more_than(series, threshold=5):
    try:
        trues = series.value_counts()[True]
        p = trues / len(series) * 100
    except KeyError:
        p = 0
    
    return True if p > threshold else False

df['compare'] = df['A'] > 5

print(more_than(df['compare']))

# True here

我希望有类似于

all(...)
的功能,但可能有阈值(如上)。它按预期工作,但我想知道是否有任何内置的东西,并且可能更快。

python pandas
1个回答
1
投票

您可以使用:

(df['A'].gt(5).mean()*100)>5

输出:

True

© www.soinside.com 2019 - 2024. All rights reserved.