【问题标题】:How to filter df by a certain date?如何按某个日期过滤df?
【发布时间】:2019-04-02 15:45:49
【问题描述】:

我有一个 df 的数据。我需要能够根据星期几返回某些数据行。

如果是星期一,我需要打印包含过去 3 天数据的行。 如果是星期三或星期五,我需要打印包含过去两天数据的行。

合并两个df创建一个:

df_new = pd.concat([outcomes_df, specialists_df], ignore_index=True)

df_new['Published Date'] = pd.to_datetime(df_new['Published Date'])

根据今天的日期获取正确的日期:

N=0
if datetime.today().weekday() == 0:
    N = 3
elif datetime.today().weekday() == 2 or datetime.today().weekday() == 4:
    N = 2
else:
    pass

mydate = datetime.now() - timedelta(days=N)
print(mydate)

按日期范围过滤

df_new = df_new[(df_new['Published Date'] >= mydate) & (df_new['Published Date'] <= datetime.today())]

print(mydate) 生成正确的日期

print(df_new) 导致错误:

空数据框 列:[col1,col2,col3,发布日期] 索引:[]

【问题讨论】:

  • 欢迎来到 StackOverflow。为了能够更好地帮助您,您应该提供您正在使用的数据以及预期输出的样子。在此处查找更多信息:stackoverflow.com/questions/20109391/…

标签: python python-3.x pandas datetime


【解决方案1】:

这里不需要 if else ,因为这也需要 for 循环,这里我使用 np.select

import numpy as np
s=df_new['Published Date'].dt.weekday
d=np.select([s==0,s.isin([2,4])],[3,2],0)


df_new['mydate']=(pd.to_datetime('today')-pd.to_timedelta(d,unit='D'))

df_new = df_new[(df_new['Published Date'] >= df_new['mydate']) & (df_new['Published Date'] <= datetime.today())]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多