fsahisl
fsahisl

Reputation: 17

Python DataFrame select row 3 years

I 5 years of stock data. and I want to select the row from the first 3 year (2015,2016, 2017) How do I do this?

Date       | Year    | Month 
2015-01-02 | 2015    | 1  
2016-01-05 | 2016    | 1  
2016-01-06 | 2016    | 1  
2017-01-07 | 2017    | 1 
2018-01-07 | 2018    | 1 

I have tired this line below:

ndf = df.loc[(df['Year'] == "2015") & (df['Year'] == "2016") & (df['Year'] == "2017")]

but it is only returning 2015.

Upvotes: 0

Views: 81

Answers (2)

Mike Organek
Mike Organek

Reputation: 12484

Are you sure it is returning rows for 2015? You have set up an AND condition that cannot be satisfied and should return an empty dataframe.

Please use this:

ndf = df.query('2015 <= Year <= 2017')

Upvotes: 1

GMB
GMB

Reputation: 222442

In SQL, that's straight-foward with in:

select *
from mytable
where year in (2015, 2016, 2017)

Upvotes: 1

Related Questions