【问题标题】:pandas How to find all rows within 10 days of any date in a list of datespandas 如何在日期列表中查找任何日期的 10 天内的所有行
【发布时间】:2021-06-27 00:43:11
【问题描述】:

我有一个日期列表,但我不能只使用df['date'].isin(list_of_dates),因为我还想要日期在我列表中某个日期的 10 天内的任何行。例如,如果我的数据框有 5 行,其日期为

  date    
02-04-21
30-03-21
22-03-21
18-03-21
12-03-21

list_of_dates = ["30-03-21", "05-03-21"]

然后我想要三个前三行,因为它们在 "30-03-21" 的 10 天内,最后一行因为它在 "05-03-21" 的 10 天内。但不是第四行。

【问题讨论】:

  • 您的日期列表可能有两个以上的条目,对吗?另外你如何定义10天?前?之后?更清楚一点,如果可以的话
  • @sammywemmy 是的,这个列表可能有很多条目,我的意思是前后 10 天,所以总共 20 天。如果多个周期重叠,那么重叠中的行应该只计算一次,尽管我们可以在事后通过删除具有相同索引的行来处理这个问题。有什么想法吗?

标签: python pandas dataframe date datetime


【解决方案1】:

目标是将列表 ["30-03-21", "05-03-21"] 更改为以下列表

Output

2021-03-30  0   
2021-03-31  0
2021-04-01  0
2021-04-02  0
2021-04-03  0
2021-04-04  0
2021-04-05  0
2021-04-06  0
2021-04-07  0
2021-04-08  0

使用 reample() 函数

list_of_dates = ["30-03-21", "05-03-21"]
df=pd.DataFrame({'Date':list_of_dates})
df['Date']=pd.to_datetime(df['Date'])
s1=df['Date'].append(
pd.Series(df.loc[0,'Date']+pd.Timedelta('9D'))).append(
pd.Series(df.loc[1,'Date']+pd.Timedelta('9D')))
df1=df1.reset_index().set_index(0)
df1=df1.sort_index()
target=df1.iloc[:2,:].resample('D').fillna(method='ffill').append(
df1.iloc[2:,:].resample('D').fillna(method='ffill'))

祝你好运~

【讨论】:

    【解决方案2】:

    我会使用pandas.date_range() 来生成所有可能的日期。

    list_of_dates = ["30-03-21", "05-03-21"]
    
    set_of_dates_expand = set()
    
    for date in list_of_dates:
        set_of_dates_expand.update(pd.date_range(start=date, periods=10))
        set_of_dates_expand.update(pd.date_range(end=date, periods=10))
    
    df['date'].isin(set_of_dates_expand)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-18
      相关资源
      最近更新 更多