要按照日期列的epoch周对多个列的Pandas进行分组,可以使用pd.Grouper
函数来实现。以下是一个示例代码:
import pandas as pd
# 创建示例数据
data = {
'date': ['2022-01-01', '2022-01-02', '2022-01-03', '2022-01-04', '2022-01-05'],
'col1': [1, 2, 3, 4, 5],
'col2': [6, 7, 8, 9, 10],
'col3': [11, 12, 13, 14, 15]
}
df = pd.DataFrame(data)
# 将日期列转换为datetime类型
df['date'] = pd.to_datetime(df['date'])
# 按照日期列的epoch周对多个列进行分组
grouped = df.groupby(pd.Grouper(key='date', freq='W'))
# 遍历分组并对每个分组进行操作
for name, group in grouped:
print('Group:', name)
print(group)
print()
输出结果:
Group: 2022-01-02 00:00:00
date col1 col2 col3
0 2022-01-01 1 6 11
1 2022-01-02 2 7 12
Group: 2022-01-09 00:00:00
date col1 col2 col3
2 2022-01-03 3 8 13
3 2022-01-04 4 9 14
4 2022-01-05 5 10 15
在代码中,首先创建了一个包含日期列和多个其他列的示例数据。然后,使用pd.to_datetime
函数将日期列转换为datetime类型。接下来,使用pd.Grouper
函数将日期列按照epoch周进行分组,并存储在grouped
变量中。最后,使用for
循环遍历分组,并对每个分组进行操作。