You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现计算y=x直线上下数据点占比的方法

计算数据点在y=x直线上下的百分比

你的代码核心错误是用DataFrame的行索引代替了数据中的x列值——只有当行索引恰好等于数据里的x值时,逻辑才成立,但大多数情况下索引只是行号,和实际x坐标无关。

正确解法

假设你的DataFrame包含明确的x列和y列,我们需要直接对比每一行的y值与x值,来统计各区域的点占比:

def calculate_line_percentages(df, x_col, y_col):
    total_points = len(df)
    if total_points == 0:
        return {"上方占比": 0, "下方占比": 0, "在直线上占比": 0}
    
    # 统计各区域的点数
    above_count = (df[y_col] > df[x_col]).sum()
    below_count = (df[y_col] < df[x_col]).sum()
    on_line_count = (df[y_col] == df[x_col]).sum()
    
    # 计算百分比(保留两位小数)
    above_percent = round((above_count / total_points) * 100, 2)
    below_percent = round((below_count / total_points) * 100, 2)
    on_line_percent = round((on_line_count / total_points) * 100, 2)
    
    return {
        "上方占比": above_percent,
        "下方占比": below_percent,
        "在直线上占比": on_line_percent
    }

使用示例

假设你的数据结构如下:

xy
10.8
22.5
33

调用函数:

# 假设df是你的数据框
result = calculate_line_percentages(df, 'x', 'y')
print(result)
# 输出:{'上方占比': 33.33, '下方占比': 33.33, '在直线上占比': 33.33}

自定义调整

如果不需要单独统计在直线上的点,可以将其合并到某一侧:

  • 把y=x的点归到下方:below_count = (df[y_col] <= df[x_col]).sum()
  • 把y=x的点归到上方:above_count = (df[y_col] >= df[x_col]).sum()

内容的提问来源于stack exchange,提问作者Saliinger

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 23:55:23