1

Get column value with condition from another column. For example I have dataframe

Package   Drink  Age   Name
Full       Tea   50    Toni
Half       Tea   50    Stark
Full       Tea   20    Evan
Half       Tea   50    Christ
Quarter    Tea   61    Mark
Quarter    Tea   18    Rufallo

Then I want to get name only '''if package==full or Half and Age =>50'''

The output I expected is

Tony
Stark
Christ

I saw some guidance in internet, then I wrote subdf= df[(df["Package"] == 'Full') | (data["Package"] == 'Half' & (data['Age'] >= 50)), 'Name']

but it is not working. the error say, 'Invalid index error'

1 Answer 1

1

Use DataFrame.loc for select only column name with mask, for check membership use Series.isin:

subdf= df.loc[df["Package"].isin([ 'Full','Half']) & (df['Age'] >= 50), 'Name']
print (subdf)
0      Toni
1     Stark
3    Christ
Name: Name, dtype: object

Your solution with multiple | for bitwise OR:

subdf= df.loc[((df["Package"] == 'Full') | (df["Package"] == 'Half')) & 
               (df['Age'] >= 50), 'Name']
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.