以下是一个示例代码,根据时间戳将数据分组,并计算其他列的平均值和总和:
import pandas as pd
# 创建示例数据
data = {'时间戳': ['2021-01-01 09:00:00', '2021-01-01 09:00:00', '2021-01-01 10:00:00', '2021-01-01 10:00:00'],
'其他列1': [10, 20, 30, 40],
'其他列2': [5, 15, 25, 35]}
df = pd.DataFrame(data)
# 将时间戳列转换为datetime类型
df['时间戳'] = pd.to_datetime(df['时间戳'])
# 根据时间戳分组,并计算其他列的平均值和总和
grouped = df.groupby(pd.Grouper(key='时间戳', freq='1H'))
result = grouped.agg({'其他列1': ['mean', 'sum'], '其他列2': ['mean', 'sum']})
print(result)
输出结果如下:
其他列1 其他列2
mean sum mean sum
时间戳
2021-01-01 09:00:00 15 30 10 20
2021-01-01 10:00:00 35 70 30 60
以上代码首先创建了一个示例数据,包含时间戳和其他两列。然后将时间戳列转换为datetime类型。接下来,使用groupby
函数根据时间戳进行分组,使用pd.Grouper
指定按小时分组。最后,使用agg
函数计算其他列的平均值和总和。输出结果显示了按时间戳分组的结果,以及其他列的平均值和总和。
下一篇:按时间戳分组后求和的问题。