[Python] pandas/numpy conversion of values based on values of several other columns (multile...

Discussão em 'Python' iniciado por Stack, Fevereiro 19, 2025.

  1. Stack

    Stack Membro Participativo

    I have a pandas dataframe which looks like this (columns names and values are not representative):

    A | B | C | D | E | F | G ...| X | Z
    a0|a0 |c0 |d0 |e0 |f0 | g0 | x0| z0
    a1|b1 |c1 |d1 |e1 |f1 | g1 | x1| z1
    a2|b2 |c2 |d2 |e2 |f2 | g2 | x2| z2
    a3|b3 |c3 |d3 |e3 |f3 | g3 | x3| z3
    a4|b4 |c4 |d4 |e4 |f4 | g4 | x4| z4
    .
    .
    axx|bxx|cxx|dxx|exx|fxx|gxx | xx| zx


    And then I have a series of rules which are the mapping requirements. The number of rules will change over time

    Something like this:

    A | B | C | D | E | F | G ...| X | Z
    a0| |c0 |d0 | | | | ns| wb
    a0|b1 | |d1 | |f4 | | cp| qk
    | |c1 |d0 |e0 |f0 | | bq| mc
    a0|b0 | | | | | j0 | os| mw
    a4| | |d4 | |f4 | | tw| px



    In other words if certain columns hold certain values for a row, then change the value of this row for either the same columns or other ones.

    What would be an efficient way to handle this problem?

    This is an AI generated answer:

    import pandas as pd
    import numpy as np

    # Your original dataframe
    df = pd.DataFrame({
    'A': ['a0', 'a1', 'a2', 'a3', 'a4'],
    'B': ['b0', 'b1', 'b2', 'b3', 'b4'],
    'C': ['c0', 'c1', 'c2', 'c3', 'c4'],
    'D': ['d0', 'd1', 'd2', 'd3', 'd4'],
    'E': ['e0', 'e1', 'e2', 'e3', 'e4'],
    'F': ['f0', 'f1', 'f2', 'f3', 'f4'],
    'X': ['x0', 'x1', 'x2', 'x3', 'x4'],
    'Z': ['z0', 'z1', 'z2', 'z3', 'z4']
    })

    # Define your rules as a list of dictionaries
    rules = [
    {'condition': {'A': 'a0', 'C': 'c0', 'D': 'd0'}, 'action': {'X': 'ns', 'Z': 'wb'}},
    {'condition': {'A': 'a0', 'B': 'b1', 'D': 'd1', 'F': 'f4'}, 'action': {'X': 'cp', 'Z': 'qk'}},
    {'condition': {'C': 'c1', 'D': 'd0', 'E': 'e0', 'F': 'f0'}, 'action': {'X': 'bq', 'Z': 'mc'}},
    {'condition': {'A': 'a0', 'B': 'b0'}, 'action': {'X': 'os', 'Z': 'mw'}},
    {'condition': {'A': 'a4', 'D': 'd4', 'F': 'f4'}, 'action': {'X': 'tw', 'Z': 'px'}}
    ]

    # Function to apply rules
    def apply_rules(df, rules):
    for rule in rules:
    # Create a boolean mask for the condition
    mask = pd.Series(True, index=df.index)
    for col, val in rule['condition'].items():
    mask &= df[col] == val

    # Apply the action where the condition is met
    for col, val in rule['action'].items():
    df.loc[mask, col] = val

    return df

    # Apply the rules
    df = apply_rules(df, rules)

    print(df)

    Continue reading...

Compartilhe esta Página