[Python] How to efficiently multiply all non-diagonal elements by a constant in a pandas...

Discussão em 'Python' iniciado por Stack, Junho 8, 2025.

  1. Stack

    Stack Membro Participativo

    I have a square cost matrix stored as a pandas DataFrame. Rows and columns represent positions [i, j], and I want to multiply all off-diagonal elements (where i != j) by a constant c, without using any for loops for performance reasons.

    Is there an efficient way to achieve this in pandas or do I have to switch to numpy and then back to pandas to perform this task?

    Example

    import pandas as pd

    # Sample DataFrame
    cost_matrix = pd.DataFrame([
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
    ])

    # Constant
    c = 4

    # Desired output
    # 1 8 12
    # 16 5 24
    # 28 16 9

    Continue reading...

Compartilhe esta Página