[Python] Pandas: effective way to change some values in DataFrame with values from Series

Discussão em 'Python' iniciado por Stack, Março 4, 2025.

  1. Stack

    Stack Membro Participativo

    I have a Pandas dataframe with some values and a Series with corresponding maximum allowed values.
    Next, I check dataframe and see, that some values are greater maximum allowed values and I need to replace them with values from Series.

    How can I do this maximum Python and Pandas way?

    Thank you!

    Example code:

    import pandas as pd

    max_vals = pd.Series([3, 4, 5, 6, 7], index=['a', 'b', 'c', 'd', 'e'])
    data = pd.DataFrame([[1,2,7,4,5],
    [2,3,4,5,6],
    [7,8,5,10,11]],
    columns=max_vals.index)

    mask = data > max_vals
    data[mask]

    a b c d e
    0 NaN NaN 7.0 NaN NaN
    1 NaN NaN NaN NaN NaN
    2 7.0 8.0 NaN 10.0 11.0

    # How can I do something like this?

    data[mask] = max_vals[mask]

    Continue reading...

Compartilhe esta Página