2

df is a pandas dataframe.

this gives me my young subjects:

df_young = df[df['Age']<40]

this gives me my old subjects:

df_old = df[df['Age']>60]

Now I want to get my middleaged subjects with something like (invalid syntax):

df_middleage = df[df['Age']< 40 and < 60]

Does anyone know how to do that efficiently? Thanks.

1 Answer 1

3

You can use &:

df_middleage = df[(df['Age'] > 40) & (df['Age'] < 60)]

See the docs here: http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. That works - but the greater-than signs should be like that: df_middleage = df[(df['Age']> 40) & (df['Age']< 60)] to get the middleaged

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.