比较日期从熊猫数据框到当前日期

时间:2019-05-11 18:51:01

标签: python pandas

我目前正在尝试编写一个脚本,该脚本会在特定的一天执行特定的操作。例如,如果今天是6/30/2019,而在我的数据框中有6/30/2019条目,则xyz继续发生。但是,我在比较从数据框到DateTime日期的日期时遇到麻烦。这是我创建数据框的方法

now = datetime.datetime.now()

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

这里是我打印数据框时输出的样子。

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

在这里'event_date'列的打印方式

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

所以我尝试了其他线程中看到的一些事情。 我尝试过:

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

返回

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

我尝试使用以下方法重新格式化数据:

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

返回此

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

我已经尝试过了

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

那又返回了

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

我不知道为什么python告诉我str是一个数据框,我假设它与python如何从excel表格中导出数据有关。我不确定该如何解决。

我只是希望python检查是否有任何行与当前日期具有相同的"event_date"值,并返回索引或返回要在循环中使用的布尔值。

2 个答案:

答案 0 :(得分:1)

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]

我建议根据同一列中的匹配项执行xy或一列中需要执行的操作。即

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

比循环更容易。

答案 1 :(得分:0)

import pandas as pd
import time 

# keep only y,m,d, and throw out the rest:
now =  (time.strftime("%Y/%m/%d"))

# the column in the dataframe needs to be converted to datetime first.
df['event_date'] = pd.to_datetime(df['event_date'])

# to return indices
df[df['event_date']==now].index.values

# if you want to loop, you can do:
for ix, row in df.iterrows():
    if row['event_date'] == now:
        print(ix)
相关问题