user11509999
user11509999

Reputation:

Python Dataframe: Assign values to a column based on condition?

I have a df with name and status with present and absent as values.

            name     status
    0      anthony   present
    1      anthony   absent
    2      mason     present
    3      donny     present
    4      donny     absent
    5      donny     absent
    6      paul      present
    7      paul      present

I'm trying to put status - True or False for each name.

If one of the name has absent their status will be False

Expected Output:

            name     output
    0      anthony   False
    1      mason     True
    2      donny     False
    3      paul      True

Upvotes: 0

Views: 117

Answers (2)

wwnde
wwnde

Reputation: 26676

Another way is to groupby name and find if a name has present as the only status.

df.groupby('name')['status'].apply(lambda x: (x=='present').all())



    name
    anthony    False
    donny      False
    mason       True
    paul        True

Upvotes: 0

Quang Hoang
Quang Hoang

Reputation: 150735

You can compare status to 'present' then get the mininum by name:

# or `all()` instead of `min()`
df['status'].eq('present').groupby(df['name']).min()

Output:

name
anthony    False
donny      False
mason       True
paul        True
Name: status, dtype: bool

Upvotes: 1

Related Questions