简体   繁体   中英

Resample a pandas dataframe with multiple variables

I have a dataframe in long format with data on a 15 min interval for several variables. If I apply the resample method to get the average daily value, I get the average values of all variables for a given time interval (and not the average value for speed, distance).

Does anyone know how to resample the dataframe and keep the 2 variables?

Note: The code below contains an EXAMPLE dataframe in long format, my real example loads data from csv and has different time intervals and frequencies for the variables, so I cannot simply resample the dataframe in wide format.

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()

IIUC:

>>> 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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM