Pandas 索引级别内的重采样频率
Pandas resample frequency within index level
在 Pandas 内,我想对我的数据框重新采样,并在 5 小时内和索引水平内取平均值。我的数据框看起来像:df
timestamp width length
name
10 2019-08-01 00:00:00 10.1 86.1
10 2019-08-01 00:00:10 10.0 86.2
10 2019-08-01 00:05:40 10.1 86.3
10 2019-08-01 00:05:50 10.0 86.2
8 2019-08-01 00:05:54 12.0 110.0
我想将我的 'name' 变量保留为索引(最好不要将时间戳设置为索引),例如:
timestamp width length
name
10 2019-08-01 00:00:05 10.05 86.15
10 2019-08-01 00:05:45 10.05 86.25
8 2019-08-01 00:05:54 12.0 110.0
我试过了:
df_resample = df.resample('5H', on='timestamp').mean()
但这不会在索引级别执行。它还在我试图避免的索引上设置日期时间。
IIUC,可以使用groupby
和resample
:
(df.groupby(level=0, sort=False)
.resample('5min', on='timestamp').mean()
.reset_index()
)
然而,这不会平均您的时间戳,因为您不能真正添加 Datetime
输入 pandas,尽管有一些解决方法。
name timestamp width length
0 10 2019-08-01 00:00:00 10.05 86.15
1 10 2019-08-01 00:05:00 10.05 86.25
2 8 2019-08-01 00:05:00 12.00 110.00
Update如果你想要mean timestamp,你可以临时将timestamp转换为int,取mean,再转换回来:
(df.assign(int_time=lambda x: x['timestamp'].astype('int64') )
.groupby(level=0, sort=False)
.resample('5min', on='timestamp').mean()
.reset_index()
.assign(timestamp=lambda x: x['int_time'].astype('int64').astype('datetime64[ns]'))
.drop('int_time', axis=1)
)
输出:
name timestamp width length
0 10 2019-08-01 00:00:05 10.05 86.15
1 10 2019-08-01 00:05:45 10.05 86.25
2 8 2019-08-01 00:05:54 12.00 110.00
临时将时间戳设置为索引,然后重新建立原始索引。
df = df.reset_index().set_index('timestamp').resample('5H').mean().set_index('name')
这是你想要得到的吗?
在 Pandas 内,我想对我的数据框重新采样,并在 5 小时内和索引水平内取平均值。我的数据框看起来像:df
timestamp width length
name
10 2019-08-01 00:00:00 10.1 86.1
10 2019-08-01 00:00:10 10.0 86.2
10 2019-08-01 00:05:40 10.1 86.3
10 2019-08-01 00:05:50 10.0 86.2
8 2019-08-01 00:05:54 12.0 110.0
我想将我的 'name' 变量保留为索引(最好不要将时间戳设置为索引),例如:
timestamp width length
name
10 2019-08-01 00:00:05 10.05 86.15
10 2019-08-01 00:05:45 10.05 86.25
8 2019-08-01 00:05:54 12.0 110.0
我试过了:
df_resample = df.resample('5H', on='timestamp').mean()
但这不会在索引级别执行。它还在我试图避免的索引上设置日期时间。
IIUC,可以使用groupby
和resample
:
(df.groupby(level=0, sort=False)
.resample('5min', on='timestamp').mean()
.reset_index()
)
然而,这不会平均您的时间戳,因为您不能真正添加 Datetime
输入 pandas,尽管有一些解决方法。
name timestamp width length
0 10 2019-08-01 00:00:00 10.05 86.15
1 10 2019-08-01 00:05:00 10.05 86.25
2 8 2019-08-01 00:05:00 12.00 110.00
Update如果你想要mean timestamp,你可以临时将timestamp转换为int,取mean,再转换回来:
(df.assign(int_time=lambda x: x['timestamp'].astype('int64') )
.groupby(level=0, sort=False)
.resample('5min', on='timestamp').mean()
.reset_index()
.assign(timestamp=lambda x: x['int_time'].astype('int64').astype('datetime64[ns]'))
.drop('int_time', axis=1)
)
输出:
name timestamp width length
0 10 2019-08-01 00:00:05 10.05 86.15
1 10 2019-08-01 00:05:45 10.05 86.25
2 8 2019-08-01 00:05:54 12.00 110.00
临时将时间戳设置为索引,然后重新建立原始索引。
df = df.reset_index().set_index('timestamp').resample('5H').mean().set_index('name')
这是你想要得到的吗?