[Python] Pandas add column with value based on condition based on other columns

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

  1. Stack

    Stack Membro Participativo

    I have the following pandas dataframe:

    [​IMG]

    import pandas as pd
    import numpy as np

    d = {'age' : [21, 45, 45, 5],
    'salary' : [20, 40, 10, 100]}

    df = pd.DataFrame(d)


    and would like to add an extra column called "is_rich" which captures if a person is rich depending on his/her salary. I found multiple ways to accomplish this:

    # method 1
    df['is_rich_method1'] = np.where(df['salary']>=50, 'yes', 'no')

    # method 2
    df['is_rich_method2'] = ['yes' if x >= 50 else 'no' for x in df['salary']]

    # method 3
    df['is_rich_method3'] = 'no'
    df.loc[df['salary'] > 50,'is_rich_method3'] = 'yes'


    resulting in:

    [​IMG]

    However I don't understand what the preferred way is. Are all methods equally good depending on your application?

    Continue reading...

Compartilhe esta Página