Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to Search specific cell in Pandas through a list of matching content [duplicate]

Tags:

python

pandas

enter image description here

I am new to python and trying to make a small program with python. My requirement : I have a list like this: holiday = ['1 January 2018','26 January 2018','2 March 2018','30 March 2018']

and I have a pandas DataFrame which print like this: enter image description here

Now I want to search for the Dates in dataframe which match with my list like "26 January 2018" and want to save that search result in a separate data frame.

I am not getting the proper way to do this. pls suggest

like image 765
Jagdish Avatar asked Jan 01 '26 08:01

Jagdish


1 Answers

1. String matching

If your date formats match, you can directly go for string matching (although it's a crude way)

df2 = df[df['date'].isin(holiday)]

2. Parsing datetime (proper way)

Parse the dates first and then go for the match!

a. Parse the df dates

df['date'] = pd.to_datetime(df['date'], format='%d %B %Y')

b. Parse the dates in the list

import datetime as dt
holiday = ['1 January 2018','26 January 2018','2 March 2018','30 March 2018']
holiday_parsed = [dt.strptime(i, format='%d %B %Y') for i in holiday]

And then do the filtering -

df2 = df[df['date'].isin(holiday_parsed)]

The .isin() is a pandas convenience method that lets you search your pandas series with a list.

Hope that helps!

like image 122
Vivek Kalyanarangan Avatar answered Jan 02 '26 20:01

Vivek Kalyanarangan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!