AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题 / 79596227
Accepted
Evan Lynch
Evan Lynch
Asked: 2025-04-28 18:15:56 +0800 CST2025-04-28 18:15:56 +0800 CST 2025-04-28 18:15:56 +0800 CST

查找列之间的数值关系

  • 772

我从数据库中选择了一个数值列的子集,并希望遍历这些列,选择一个,target_column并将其与数据框中其他两列之间的数值运算结果进行比较。但是,我不确定如何比较结果(例如col1 * col2 = target_column)。

# For all possible combinations of numeric columns
for col1, col2 in combinations(numeric_cols, 2):
    # For a target column in numeric_columns
    for target_column in numeric_cols:
        # Skip if the target column is one of the relationship columns
        if target_column in (col1, col2):
            continue

编辑:我已经解决了一些问题,但我仍然不确定这是否是最有效的方法

def analyse_relationships(df):

numeric_cols = df.select_dtypes(include=[np.number])
threshold = 0.001
relationships = []

# For all possible combinations of numeric columns
for col1, col2 in combinations(numeric_cols, 2):
    # For a target column in numeric_columns
    for target_column in numeric_cols:
        # Skip if the target column is one of the relationship columns
        if target_column in (col1, col2):
            continue

        # Calculate different operations
        product = numeric_cols[col1] * numeric_cols[col2]
        sum_cols = numeric_cols[col1] + numeric_cols[col2]
        diff = numeric_cols[col1] - numeric_cols[col2]

        if np.allclose(product, numeric_cols[target_column], rtol=threshold):
            relationships.append(f"{col1} * {col2} = {target_column}")
        elif np.allclose(sum_cols, numeric_cols[target_column], rtol=threshold):
            relationships.append(f"{col1} + {col2} = {target_column}")
        elif np.allclose(diff, numeric_cols[target_column], rtol=threshold):
            relationships.append(f"{col1} - {col2} = {target_column}")
python
  • 1 1 个回答
  • 55 Views

1 个回答

  • Voted
  1. Best Answer
    CcmU
    2025-04-28T20:56:25+08:002025-04-28T20:56:25+08:00

    为了解决您的问题,我强烈建议您对数据进行矢量化,并尽可能少地使用 Pandas 操作,因为需要进行大量操作,因此,我们越依赖 NumPy,代码运行速度就越快(NumPy 的核心是用 C 编写的)。

    由于需要考虑多个运算(+,-,*,/),我们需要计算每个结果并将其与 进行比较target_column,但我们可以使用布尔掩码(即NumPy 数组)来提高空间效率,该掩码是以布尔值表示表达式 的列target_column == col1 operation col2。请注意,由于 中可能存在浮点数df,因此实际上最好使用 ,numpy.isclose()以便为浮点运算设置阈值。

    您的代码可能类似于以下内容(我在最后添加了一个小示例):

    import numpy as np
    import pandas as pd
    from itertools import combinations
    
    def detect_relations(df, numeric_cols, float_tolerance=1e-8):
        results = []
        ops = {
            "+": [(lambda x, y: x + y, "a + b")],   # No need to have `b + a` since sum is commutative
            "-": [
                (lambda x, y: x - y, "a - b"),
                (lambda x, y: y - x, "b - a")
            ],
            "*": [(lambda x, y: x * y, "a * b")],   # Same as sum, `a * b = b * a`
            "/": [
                # We need to ensure that we don't divide by 0
                (lambda x, y: np.divide(x, y, out=np.full_like(x, np.nan, dtype=float), where=(y != 0)), "a / b"),
                (lambda x, y: np.divide(y, x, out=np.full_like(x, np.nan, dtype=float), where=(x != 0)), "b / a")
            ],
        }
        # Iterating trough every combination
        for col1, col2 in combinations(numeric_cols, 2):
            a = df[col1].values
            b = df[col2].values
            # Iterating trough each possible operation
            for _, functions in ops.items():
                for func, op_name in functions:
                    # Calculating the result of the operation `func` between col1 and col2
                    val = func(a, b)
                    # Confronting the result of `col1 operation col2` to the other numeric columns (avoiding col1 and col2)
                    for target in numeric_cols:
                        if target in (col1, col2):
                            continue
                        c = df[target].values
                        # We get a boolean mask with the comparison between `col1 operation col2` and `target_column`
                        mask = np.isclose(val, c, atol=float_tolerance, equal_nan=False)
                        # Counting how many relations we found
                        matches = int(mask.sum())
                        total = len(df)
                        
                        results.append({
                            "col1": col1,
                            "col2": col2,
                            "operation": op_name,
                            "target": target,
                            "matches": matches,
                            "total": total,
                            "pct_match": matches / total
                        })
                    
        return pd.DataFrame(results)
    
    
    # --- Example---
    df = pd.DataFrame({
        "a": [1, 2, 3, 4],
        "b": [2, 2, 2, 2],
        "c": [2, 4, 6, 8],
        "d": [2, 0, 1, 8],
    })
    
    numeric_cols = ["a", "b", "c", "d"]
    res = detect_relations(df, numeric_cols)
    # Avoid to print combinations with no relation
    print(res[res["matches"] > 0].sort_values("pct_match", ascending=False))
    

    输出:

       col1 col2 operation target  matches  total  pct_match
    6     a    b     a * b      c        4      4       1.00
    22    a    c     b / a      b        4      4       1.00
    46    b    c     b / a      a        4      4       1.00
    7     a    b     a * b      d        2      4       0.50
    48    b    d     a + b      a        2      4       0.50
    26    a    d     a - b      b        2      4       0.50
    58    b    d     b / a      a        2      4       0.50
    34    a    d     b / a      b        2      4       0.50
    3     a    b     a - b      d        2      4       0.50
    5     a    b     b - a      d        1      4       0.25
    0     a    b     a + b      c        1      4       0.25
    19    a    c     a * b      d        1      4       0.25
    18    a    c     a * b      b        1      4       0.25
    16    a    c     b - a      b        1      4       0.25
    11    a    b     b / a      d        1      4       0.25
    10    a    b     b / a      c        1      4       0.25
    30    a    d     a * b      b        1      4       0.25
    24    a    d     a + b      b        1      4       0.25
    23    a    c     b / a      d        1      4       0.25
    40    b    c     b - a      a        1      4       0.25
    35    a    d     b / a      c        1      4       0.25
    31    a    d     a * b      c        1      4       0.25
    44    b    c     a / b      a        1      4       0.25
    50    b    d     a - b      a        1      4       0.25
    56    b    d     a / b      a        1      4       0.25
    68    c    d     a / b      a        1      4       0.25
    70    c    d     b / a      a        1      4       0.25
    

    复杂性分析

    我想指出的是,上面的代码有一定的时间复杂度,当元素数量很大时可能会很慢。

    上面的代码必须经过多次循环:

    • 通过的每一个组合numerical_cols,即(m choose 2) = m(m-1)/2 ~ O(m^2);
    • 尽一切可能target,即O(m - 2) = O(m);
    • numpy.isclose()通过循环遍历每个元素进行的比较n,因此其复杂度为O(n)。

    考虑到这些周期,很容易看出代码的时间复杂度为O(m^2 * m * n) = O(n * m^3),因此所需时间将相对于数值列的数量呈立方增加,并且相对于每列中的元素数量呈线性增加。

    • 1

相关问题

  • 如何将 for 循环拆分为 3 个单独的数据框?

  • 如何检查 Pandas DataFrame 中的所有浮点列是否近似相等或接近

  • “load_dataset”如何工作,因为它没有检测示例文件?

  • 为什么 pandas.eval() 字符串比较返回 False

  • Python tkinter/ ttkboostrap dateentry 在只读状态下不起作用

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    重新格式化数字,在固定位置插入分隔符

    • 6 个回答
  • Marko Smith

    为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会?

    • 2 个回答
  • Marko Smith

    VScode 自动卸载扩展的问题(Material 主题)

    • 2 个回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Martin Hope
    Fantastic Mr Fox msvc std::vector 实现中仅不接受可复制类型 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant 使用 chrono 查找下一个工作日 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor 构造函数的成员初始化程序可以包含另一个成员的初始化吗? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský 为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul C++20 是否进行了更改,允许从已知绑定数组“type(&)[N]”转换为未知绑定数组“type(&)[]”? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann 为什么 {2,3,10} 和 {x,3,10} (x=2) 的顺序不同? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve