我如何在大熊猫中按10秒组分组

时间:2017-08-07 22:02:42

标签: python pandas time-series

我每10秒收集一次数据。我希望按照10秒组进行分组,以便与每组进行比较。所以我将有6组(00,10,20,30,40,50)。然后我可以使用每个系列/组的方框图。

我尝试使用石斑鱼但没有成功。

groups = df.reset_index().groupby(pd.Grouper(key='date', freq='10s', axis=1))

以下是一小部分数据。

                      value
date                       
2012-01-01 01:00:00    5.0
2012-01-01 01:00:10   16.5
2012-01-01 01:00:20   28.5
2012-01-01 01:00:30   40.5
2012-01-01 01:00:40   43.2     
2012-01-01 01:00:50   33.2 
2012-01-01 01:01:00   15.0
2012-01-01 01:01:10   14.5
2012-01-01 01:01:20   38.5
2012-01-01 01:01:30   30.5
2012-01-01 01:01:40   33.2     
2012-01-01 01:01:50   23.2 

3 个答案:

答案 0 :(得分:3)

如果您有datetime索引,则可以按索引的 second 进行分组:

df.index = pd.to_datetime(df.index)
df.groupby(df.index.second).sum()

#  value
#0  20.0
#10 31.0
#20 67.0
#30 71.0
#40 76.4
#50 56.4

答案 1 :(得分:1)

IIUC,您不需要对数据进行分组,只需要一个新的列数秒,以及该列值的框图:

首先确保您的索引是datetimeindex

df.index = pd.to_datetime(df.index)

df['10_second'] = df.index.second
df.boxplot('value','10_second')

enter image description here

答案 2 :(得分:0)

创建一个新列,该列获取日期列中的值(我们将调用此x)并提供x.timestamp() % 10)。这将给你10秒的值。

df['timestamp'] = df.apply(lambda row: x.timestamp() % 10, axis=1)

接下来,use可以使用group-by覆盖此新列中的值来对数据进行分组。

或者,如果您需要按10秒的增量分解,而不是分成6组,每组10个,您可以这样做:

df['timestamp'] = df.apply(lambda row: 10*(x.timestamp() // 10), axis=1)