Jamil Rahman
Jamil Rahman

Reputation: 335

How to filter a string in a column of Pandas data frame using for loop

How can I use 'for' loop (e.g. 'for i in range(1996,2000,1)') in string filtering of Pandas data frame ?

I have a data frame like this:

Date            Value
07/09/1997      505
05/03/1998      1005
03/02/2000      747
01/05/1998      448
06/08/1996      57
09/11/2000      673

I like to filter '1998' from the 'Date' column using a 'for i in range(1996,2000,1)' loop and create a new DF so that it would look like this:

Date            Value
05/03/1998      1005
01/05/1998      448

Upvotes: 1

Views: 250

Answers (2)

Mayank Porwal
Mayank Porwal

Reputation: 34046

for loops are slower, should be ideally avoided if possible.

Convert Date column to datetime using pd.to_datetime and then extract only year using Series.dt.year:

In [2441]: df.Date = pd.to_datetime(df.Date)
In [2446]: df = df[df.Date.dt.year.eq(1998)]

In [2447]: df
Out[2447]: 
        Date  Value
1 1998-05-03   1005
3 1998-01-05    448

Additionally, per @CainãMaxCouto-Silva's comment:

You can filter a range of years as well:

In [2451]: df[df.Date.dt.year.isin(range(1996,2000))]
Out[2451]: 
        Date  Value
0 1997-07-09    505
1 1998-05-03   1005
3 1998-01-05    448
4 1996-06-08     57

Upvotes: 3

wwnde
wwnde

Reputation: 26676

Another way

df.Date = pd.to_datetime(df.Date)
df[df.Date.dt.isocalendar().year.eq(1998)]



        Date  Value
1 1998-05-03   1005
3 1998-01-05    448

Upvotes: 1

Related Questions