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'
CodePudding user response:
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']