itstoocold
itstoocold

Reputation: 2573

How to use existing pandas df to return new df that fits specific criteria?

I have a pandas df that has three columns, name, age, and height. I want to return a new df that contains all the people with age greater than 10. What would be the command to do this?

Upvotes: 1

Views: 47

Answers (3)

jezrael
jezrael

Reputation: 863301

Solution with query:

print (df.query('age > 10'))

Sample:

df = pd.DataFrame({'name': ['a', 'b', 'c', 'd'],
                   'age': [80, 50, 10, 6],
                   'height_inches': [10, 20, 30, 40]})

print (df)
   age  height_inches name
0   80             10    a
1   50             20    b
2   10             30    c
3    6             40    d

print (df.query('age > 10'))
   age  height_inches name
0   80             10    a
1   50             20    b

Upvotes: 1

prooffreader
prooffreader

Reputation: 2453

df = pd.DataFrame({'name': ['Alice', 'Bob', 'Charles', 'Darlene'],
                   'age': [8, 11, 4, 61],
                   'height_inches': [38, 49, 25, 61]})

df_new = df[df.age > 10]

Upvotes: 2

Alexey Trofimov
Alexey Trofimov

Reputation: 5027

This is how you make such slices:

df[df['age'] > 10]

This is made by passing boolean series.

Upvotes: 1

Related Questions