[Python] Finding Numerical Relationships between Columns

Discussão em 'Python' iniciado por Stack, Abril 28, 2025.

  1. Stack

    Stack Membro Participativo

    So I have selected a subset of numerical columns from a database - I want to iterate through the columns selecting a target column and comparing it with the result of a numerical operation between two other columns in the dataframe however I am unsure as to how to compare the 'result' e.g. col1 multiplied by col 2 = 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


    Edit** I have worked something out but still unsure if this is the most efficient way to do it - Ignore threshold

    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}")

    Continue reading...

Compartilhe esta Página