[Python] How to subtract data between columns that have same subfix

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

  1. Stack

    Stack Membro Participativo

    I have a sample dataframe as below that has same subfix as 001, 002, 003.

    import pandas as pd
    import numpy as np

    branch_names = [f"Branch_{i}" for i in range(1, 11)]
    date_1 = '20241231'
    date_2 = '20250214'
    date_3 = '20250220'

    data = {
    'Branch': branch_names,
    date_1 + '_001': np.random.randint(60, 90, 10),
    date_1 + '_002': np.random.randint(60, 90, 10),
    date_1 + '_003': np.random.randint(60, 90, 10),
    date_2 + '_001': np.random.randint(60, 90, 10),
    date_2 + '_002': np.random.randint(60, 90, 10),
    date_2 + '_003': np.random.randint(60, 90, 10),
    date_3 + '_001': np.random.randint(60, 90, 10),
    date_3 + '_002': np.random.randint(60, 90, 10),
    date_3 + '_003': np.random.randint(60, 90, 10)
    }

    # Chuyển thành DataFrame
    df = pd.DataFrame(data)


    [​IMG]

    Now I want to subtract data between columns that have same subfix as below principle:

    df['diff_1_001'] = df[date_3 + '_001'] - df[date_2 + '_001']
    df['diff_2_001'] = df[date_3 + '_001'] - df[date_1 + '_001']
    df['diff_1_002'] = df[date_3 + '_002'] - df[date_2 + '_002']
    df['diff_2_002'] = df[date_3 + '_002'] - df[date_1 + '_002']
    df['diff_1_003'] = df[date_3 + '_003'] - df[date_2 + '_003']
    df['diff_2_003'] = df[date_3 + '_003'] - df[date_1 + '_003']
    df


    As you see that we have same 001, 002, 003 but prefix is different. So I want don't want to hard code the 001, 002, 003 but automatically subtract it as mentioned above.

    Continue reading...

Compartilhe esta Página