1

enter image description here

I would like to find the average age of people who have a dog using a lambda function,

and so far I have made this code

pets['age'].mean(lambda x: x in pets['pets'] == 'dog')

... but it keeps giving me a value error..... help would be very appriciated!

1
  • What number is expected output? Commented Mar 23, 2020 at 5:53

2 Answers 2

1

If need age with dog and possible another values filter by boolean indexing with DataFrame.loc:

out = df.loc[df['pets'].apply(lambda x: 'dog' in x), 'age'].mean()
print (out)
46.75

If need age with only dog :

out = df.loc[df['pets'].apply(lambda x: x[0] == 'dog'), 'age'].mean()

out = df.loc[df['pets'].str[0] == 'dog', 'age'].mean()
print (out)
55.333333333333336
Sign up to request clarification or add additional context in comments.

Comments

0

You can do the job also without any lambda function. One of possible solutions is:

df.explode('pets').query('pets == "dog"').age.mean()

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.