【问题标题】:Looking for a way to group by a datetime if datetime between two dates using Pandas of Python如果使用 Python 的 Pandas 在两个日期之间的日期时间,寻找一种按日期时间分组的方法
【发布时间】:2020-10-07 22:48:06
【问题描述】:

我正在尝试使用 Pandas (Python) 执行以下操作。

我有一个包含以下列的数据框:

建筑物、Door_Color、Door_Time_Open、Door_Time_Close、Opening_Width

我正在尝试按日期和时间对数据进行分组,这样我每秒都会计算打开的门数和 width_of_opening 的总和。

例如:

Data:
Building, Door_Color, Door_Time_Open, Door_Time_Close, Opening_Width
A , Red , 2000-01-01 00:00:00, 2000-01-01 00:00:05, 10
A , Red , 2000-01-01 00:00:02, 2000-01-01 00:00:04, 5

Result:
Date, Building, Door_Color, Door_Count, Sum_Opening_Width
2000-01-01 00:00:00, A, Red, 1 , 10
2000-01-01 00:00:01, A, Red, 1 , 10
2000-01-01 00:00:02, A, Red, 2 , 15
2000-01-01 00:00:03, A, Red, 2 , 15
2000-01-01 00:00:04, A, Red, 2 , 15
2000-01-01 00:00:05, A, Red, 1 , 10
2000-01-01 00:00:06, A, Red, 0 , 0

我知道如何按多列进行常规分组并分别聚合不同的列,但我不知道如何让机器检查我们分组的日期是否介于数据中的两个日期之间。

任何帮助将不胜感激!

edit1:数据有点大,大约600万行。

【问题讨论】:

    标签: python pandas date datetime


    【解决方案1】:

    如果数据不是太大(覆盖时间长),可以做交叉合并:

    times = pd.DataFrame({'Date':pd.date_range(df['Door_Time_Open'].min(), 
                                               df['Door_Time_Close'].max(), freq='s'),
                          'dummy':1
                         })
    
    
    (df.assign(dummy=1)
       .merge(times, on='dummy')
       .query('Door_Time_Open<=Date<=Door_Time_Close')
       .groupby(['Date','Building','Door_Color'])
       ['Opening_Width'].agg(['count','sum'])
       .reset_index()
    )
    

    输出:

                     Date Building Door_Color  count  sum
    0 2000-01-01 00:00:00       A        Red       1   10
    1 2000-01-01 00:00:01       A        Red       1   10
    2 2000-01-01 00:00:02       A        Red       2   15
    3 2000-01-01 00:00:03       A        Red       2   15
    4 2000-01-01 00:00:04       A        Red       2   15
    5 2000-01-01 00:00:05       A        Red       1   10
    

    【讨论】:

    • 它拒绝运行。刚刚给了我一个“MemoryError”。不过我很感激你的努力!
    【解决方案2】:

    处理每一行的时间然后分组

    def news(r):
        df1 = pd.DataFrame()
        df1['Date'] = pd.date_range(r['Door_Time_Open'],r['Door_Time_Close'],freq='s')
        for idx in ['Building','Door_Color','Opening_Width']:
            df1[idx] = r[idx]
        return df1
    
    df['Door_Time_Open'] = pd.to_datetime(df['Door_Time_Open'])
    df['Door_Time_Close'] = pd.to_datetime(df['Door_Time_Close'])
    df_list = []
    for idx,row in df.iterrows():
        df_list.append(news(row))
    data = pd.concat(df_list).groupby(['Date','Building','Door_Color'])['Opening_Width'].agg(['count','sum'])
    print(data)
    

    【讨论】:

    • 32 GB 的 RAM 不足以在不到 1 GB 的数据上运行此答案。
    猜你喜欢
    • 2017-01-16
    • 2017-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-07
    相关资源
    最近更新 更多