如何使用Pandas按10分钟的时间序列分组?

2024-03-29 13:20:25 发布

您现在位置:Python中文网/ 问答频道 /正文

有一个由DatatimeIndex索引的时间序列(ts),希望将其分组为10分钟

index   x  y  z

ts1     ....
ts2     ....
...

我知道如何按1分钟分组

def group_by_minute(timestamp):
    year = timestamp.year
    month = timestamp.month
    day = timestamp.day
    hour = timestamp.hour
    minute = timestamp.minute
    return datetime.datetime(year, month, day, hour, minute)

那么

ts.groupby(group_by_minute, axis=0)

我的定制功能(大致)

def my_function(group):
    first_latitude = group['latitude'].sort_index().head(1).values[0]
    last_longitude = group['longitude'].sort_index().tail(1).values[0]
    return first_latitude - last_longitude

所以ts数据帧应该包含“纬度”和“经度”列

使用TimeGrouper时

   ts.groupby(pd.TimeGrouper(freq='100min')).apply(my_function)

我犯了以下错误

TypeError: cannot concatenate a non-NDFrame object

Tags: datetimeindexbyreturndefgroupyeartimestamp
2条回答

对于这类事情,有一个pandas.TimeGrouper你所描述的是:

agg_10m = df.groupby(pd.TimeGrouper(freq='10Min')).aggregate(numpy.sum) #or other function

我知道这已经很旧了,但是pd.Grouper()也可以实现这一点:

agg_10m = df.groupby(pd.Grouper(freq='10Min')).aggregate(numpy.sum)

相关问题 更多 >