Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
223 views
in Technique[技术] by (71.8m points)

python - Comparing date from pandas dataframe to current date

I'm currently trying to write a script that does a specific action on a certain day. So for example, if today is the 6/30/2019 and in my dataframe there is a 6/30/2019 entry, xyz proceeds to happen. However, I am having troubles comparing the date from a dataframe to a DateTime date. Here's how I created the dataframe

now = datetime.datetime.now()

Test1 = pd.read_excel(r"some path")

Heres what the output looks like when I print the dataframe.

  symbol  ...                  phase
0   MDCO  ...                Phase 2
1   FTSV  ...              Phase 1/2
2    NVO  ...                Phase 2
3    PFE  ...  PDUFA priority review
4   ATRA  ...                Phase 1

Heres' how the 'event_date' column prints out

0    05/18/2019
1    06/30/2019
2    06/30/2019
3    06/11/2019
4    06/29/2019

So I've tried a few things I've seen in other threads. I've tried:

if (Test1['event_date'] == now):
    print('True')

That returns

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

I've tried reformatting my the data with:

column_A = datetime.strptime(Test1['event_date'], '%m %d %y').date()

which returns this

TypeError: strptime() argument 1 must be str, not Series

I've tried this

   if any(Test1.loc(Test1['event_date'])) == now:

and that returned this

TypeError: 'Series' objects are mutable, thus they cannot be hashed

I don't know why python is telling me the str is a dataframe, I'm assuming it has something to do with how python exports data from an excel sheet. I'm not sure how to fix this.

I simply want python to check if any of the rows have the same "event_date" value as the current date and return the index or return a boolean to be used in a loop.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
import datetime
import pandas as pd

da = str(datetime.datetime.now().date())
# converting the column to datetime, you can check the dtype of the column by doing
# df['event_date'].dtypes
df['event_date'] = pd.to_datetime(df['event_date'])    

# generate a df with rows where there is a match
df_co = df.loc[df['event_date'] == da]

I would suggest doing xy or what is required in a column based on the match in the same column. i.e.

df.loc[df['event_date'] == da,'column name'] = df['x'] + df['y']

Easier than looping.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...