使用pandas对数据帧进行时间分级

Jos*_*osh 6 python 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
Run Code Online (Sandbox Code Playgroud)

随着测量时间每天都在变化,我决定使用分箱来组织数据,然后计算每个箱子的平均值和STD,然后我可以绘制.我的想法是创建一个带有分档的最终数据框和测量的X的平均值,"观察"栏目只是为了帮助理解:

        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
Run Code Online (Sandbox Code Playgroud)

然而,我遇到了使用pd.cut和pd.groupby时间,日期时间,日期时间64,时间和分组之间不兼容的困难,基本上我觉得我在黑暗中做刺,不知道'正确'解决这个问题的方法.我能想到的唯一解决方案是通过数据帧逐行迭代,但我真的想避免这样做.

tnk*_*epp 6

每当我将时间序列数据按时间范围(这看起来就像你在这里所做的那样)时,我只需创建一个"一小时"列并切片.此外,我通常将索引设置为日期时间值...虽然这不是必需的.

# 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()
Run Code Online (Sandbox Code Playgroud)

我认为这里有一种使用df.resample的方法,但是你的时间序列中定义的开始/结束点很少,我认为这可能需要比上面的方法更多的关注.

这是否与您想要的一致?


Tre*_*ney 6

  • bin a 的正确方法pandas.DataFrame是使用pandas.cut
  • 验证日期列的datetime格式为pandas.to_datetime.
  • 使用.dt.hour提取小时,在使用.cut方法。
  • 测试在python 3.8.11pandas 1.3.1

bin数据如何

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
Run Code Online (Sandbox Code Playgroud)

通过...分组 '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
Run Code Online (Sandbox Code Playgroud)