[英]Resample a pandas dataframe with multiple variables
我有一個長格式的數據幀,其中包含多個變量的 15 分鍾間隔數據。 如果我應用重采樣方法來獲得平均每日值,我將獲得給定時間間隔內所有變量的平均值(而不是速度、距離的平均值)。
有誰知道如何重新采樣數據框並保留 2 個變量?
注意:下面的代碼包含一個長格式的示例數據幀,我的真實示例從 csv 加載數據,並且變量具有不同的時間間隔和頻率,因此我不能簡單地以寬格式重新采樣數據幀。
import pandas as pd
import numpy as np
dti = pd.date_range('2015-01-01', '2015-12-31', freq='15min')
df = pd.DataFrame(index = dti)
# Average speed in miles per hour
df['speed'] = np.random.randint(low=0, high=60, size=len(df.index))
# Distance in miles (speed * 0.5 hours)
df['distance'] = df['speed'] * 0.25
df.reset_index(inplace=True)
df2 = df.melt (id_vars = 'index')
df3 = df2.resample('d', on='index').mean()
IUC:
>>> df.groupby(df.index.date).mean()
speed distance
2015-01-01 29.562500 7.390625
2015-01-02 31.885417 7.971354
2015-01-03 30.895833 7.723958
2015-01-04 30.489583 7.622396
2015-01-05 28.500000 7.125000
... ... ...
2015-12-27 28.552083 7.138021
2015-12-28 29.437500 7.359375
2015-12-29 29.479167 7.369792
2015-12-30 28.864583 7.216146
2015-12-31 48.000000 12.000000
[365 rows x 2 columns]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.