如何在pandas数据框中分组时间?

19

我试图使用pandas数据框分析测量值“X”在几周内的平均每日波动,但时间戳/日期等特别麻烦。花费了好几个小时尝试解决这个问题,我的代码变得越来越混乱,我不认为我离解决方案更近了,希望这里有人能指导我朝着正确的方向前进。

我在不同时间和不同日期测量了X,并将每日结果保存到具有以下形式的数据框中:

    Timestamp(datetime64)         X 

0    2015-10-05 00:01:38          1
1    2015-10-05 06:03:39          4 
2    2015-10-05 13:42:39          3
3    2015-10-05 22:15:39          2

由于测量时间每天都在变化,我决定使用分箱法来组织数据,然后计算每个箱的平均值和标准差,然后将它们绘制出来。我的想法是创建一个最终的数据框,其中包含各个箱的平均X值以及测量结果的“Observations”列仅用于帮助理解:

        Time Bin       Observations     <X>  

0     00:00-05:59      [ 1 , ...]       2.3
1     06:00-11:59      [ 4 , ...]       4.6
2     12:00-17:59      [ 3 , ...]       8.5
3     18:00-23:59      [ 2 , ...]       3.1

然而,我在使用pd.cutpd.groupby进行分箱时遇到了时间、日期、日期时间、时间差等不兼容的困难,基本上我感觉自己像是在盲目尝试,没有任何关于正确解决这个问题的思路。我能想到的唯一解决方案就是逐行迭代整个数据框,但我真的很想避免这样做。

5个回答

20
  • pandas.DataFrame数据进行分组的正确方式是使用pandas.cut函数。
  • 使用pandas.to_datetime函数验证日期列是否为datetime格式。
  • 使用.dt.hour提取小时数,以在.cut方法中使用。
  • python 3.8.11pandas 1.3.1中测试通过

如何对数据进行分组

import pandas as pd
import numpy as np  # for test data
import random  # for test data

# setup a sample dataframe; creates 1.5 months of hourly observations
np.random.seed(365)
random.seed(365)
data = {'date': pd.bdate_range('2020-09-21', freq='h', periods=1100).tolist(),
        'x': np.random.randint(10, size=(1100))}
df = pd.DataFrame(data)

# the date column of the sample data is already in a datetime format
# if the date column is not a datetime, then uncomment the following line
# df.date= pd.to_datetime(df.date)

# define the bins
bins = [0, 6, 12, 18, 24]

# add custom labels if desired
labels = ['00:00-05:59', '06:00-11:59', '12:00-17:59', '18:00-23:59']

# add the bins to the dataframe
df['Time Bin'] = pd.cut(df.date.dt.hour, bins, labels=labels, right=False)

# display(df.head())
                  date  x     Time Bin
0  2020-09-21 00:00:00  2  00:00-05:59
1  2020-09-21 01:00:00  4  00:00-05:59
2  2020-09-21 02:00:00  1  00:00-05:59
3  2020-09-21 03:00:00  5  00:00-05:59
4  2020-09-21 04:00:00  2  00:00-05:59

# display(df.tail())
                    date  x     Time Bin
1095 2020-11-05 15:00:00  2  12:00-17:59
1096 2020-11-05 16:00:00  3  12:00-17:59
1097 2020-11-05 17:00:00  1  12:00-17:59
1098 2020-11-05 18:00:00  2  18:00-23:59
1099 2020-11-05 19:00:00  2  18:00-23:59

按时间间隔分组 'Time Bin'

# groupby Time Bin and aggregate a list for the observations, and mean
dfg = df.groupby('Time Bin', as_index=False)['x'].agg([list, 'mean'])

# change the column names, if desired
dfg.columns = ['X Observations', 'X mean']

# display(dfg)
                      X Observations    X mean
Time Bin                                 
00:00-05:59  [2, 4, 1, 5, 2, 2, ...]  4.416667
06:00-11:59  [9, 8, 4, 0, 3, 3, ...]  4.760870
12:00-17:59  [7, 7, 7, 0, 8, 4, ...]  4.384058
18:00-23:59  [3, 2, 6, 2, 6, 8, ...]  4.459559

8
每当我按时间范围对时间序列数据进行分组时,就会创建一个“小时”列并在其上切片。此外,通常将索引设置为日期时间值...虽然这里不需要。
# assuming your "timestamp" column is labeled ts: 
df['hod'] = [r.hour for r in df.ts]

# now you can calculate stats for each bin
ave = df[ (df.hod>=0) & (df.hod<6) ].mean()

我认为可以使用df.resample方法来处理这个问题,但是由于你的时间序列起点和终点定义不够清晰,所以可能需要比上面的方法更多的注意。

这符合您的期望吗?


2

我不确定我的答案是否最佳,但我认为它可以解决问题。
首先,我会将datetime64转换为datetime,例如使用此帖子:在datetime、Timestamp和datetime64之间进行转换

然后,如果我们假设你的第一列具有datetime并且名为TimeStamp,我会这样做:

def bin_f(x):
    if x.time() < datetime.time(6):
        return "00:00-05:59"
    elif x.time() < datetime.time(12):
        return "06:00-11:59"
    elif x.time() < datetime.time(18):
        return "12:00-17:59"
    else:
        return "18:00-23:59"

df["Bin"] = df["TimeStamp"].apply(bin_f)
grouped = df.groupby("Bin")
grouped['X'].agg(np.std)

其中X是你的列的名称。


1

虽然这是一个旧的主题,但添加另一种方法。 使用pandas resample方法可以用更少的代码实现所需的结果。

data = {'date': pd.bdate_range('2020-09-21', freq='h', periods=24).tolist(),
    'x': np.random.randint(10, size=(24))}
df = pd.DataFrame(data)
df
# This line will resample data by 6H timeframe
dfrs=df.resample('6H',on='date').agg({'x':[list,'mean']})
dfrs
                        X Observations    X mean
date                                             
2020-09-21 00:00:00  [2, 4, 1, 5, 2, 2]  2.666667
2020-09-21 06:00:00  [9, 8, 4, 0, 3, 3]  4.500000
2020-09-21 12:00:00  [7, 7, 7, 0, 8, 4]  5.500000
2020-09-21 18:00:00  [3, 2, 6, 2, 6, 8]  4.500000

0

我发现Mathiou的回答对我的目的很有帮助,但我做了以下修改:

def bin_f(x):
    h = x.time()
    if h < 6:
        return "00:00-05:59"
    elif h < 12:
        return "06:00-11:59"
    elif h < 18:
        return "12:00-17:59"
    else:
        return "18:00-23:59"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接