【问题标题】:Remove the weekend days from the event log - Pandas从事件日志中删除周末 - Pandas
【发布时间】:2021-12-10 22:20:56
【问题描述】:

您能帮我解决以下问题吗?

我需要从数据框中删除周末天数(附加链接:dataframe_running_example。我可以获得从事件中提取的混合日期和最大日期之间的所有周末天数的列表,但是我无法根据“list_excluded”列表。

  from datetime import timedelta, date
  import pandas as pd
    
    #Data Loading
    df= pd.read_csv("running-example.csv", delimiter=";")
    df["timestamp"] = pd.to_datetime(df["timestamp"])
    df["timestamp_date"] = df["timestamp"].dt.date
    
    def daterange(date1, date2):
        for n in range(int ((date2 - date1).days)+1):
            yield date1 + timedelta(n)
    
    #start_dt & end_dt
    start_dt = df["timestamp"].min()
    end_dt = df["timestamp"].max()
    print("Start_dt: {} & end_dt: {}".format(start_dt, end_dt))
    
    weekdays = [6,7]
    
    #List comprehension
    
    list_excluded = [dt for dt in daterange(start_dt, end_dt) if dt.isoweekday() in weekdays]
    df.info()
    df_excluded = pd.DataFrame(list_excluded).rename({0: 'timestamp_excluded'}, axis='columns')
    df_excluded["ts_excluded"] = df_excluded["timestamp_excluded"].dt.date
    df[~df["timestamp_date"].isin(df_excluded["ts_excluded"])]

【问题讨论】:

    标签: python pandas data-science


    【解决方案1】:

    哦,问题已解决。我使用了 pd.bdate_range() 函数。

    from datetime import timedelta, date
    import pandas as pd
    import numpy as np
    
    #Wczytanie danych
    df= pd.read_csv("running-example.csv", delimiter=";")
    df["timestamp"] = pd.to_datetime(df["timestamp"])
    df["timestamp_date"] = df["timestamp"].dt.date
    
    #Zakres timestamp: start_dt & end_dt
    start_dt = df["timestamp"].min()
    end_dt = df["timestamp"].max()
    print("Start_dt: {} & end_dt: {}".format(start_dt, end_dt))
    
    bus_days = pd.bdate_range(start_dt, end_dt)
    df["timestamp_date"] = pd.to_datetime(df["timestamp_date"])
    df['Is_Business_Day'] = df['timestamp_date'].isin(bus_days)
    df[df["Is_Business_Day"]!=False]
    

    【讨论】:

    • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-25
    • 2016-12-24
    • 1970-01-01
    • 1970-01-01
    • 2015-12-29
    相关资源
    最近更新 更多