要按日期对象创建分组,我们可以使用pandas中的cut函数。此外,我们还需要一些辅助函数来获取日期对象,将其转换为可分组的值,并设置分组标签。
以下是示例代码:
import pandas as pd
import datetime as dt
# 辅助函数-获取日期对象
def get_date_obj(date_str):
year, month, day = map(int, date_str.split('-'))
return dt.date(year, month, day)
# 辅助函数-将日期对象转换为可分组的值
def get_date_group(date_obj):
return date_obj.strftime('%Y-%m')
# 辅助函数-设置分组标签
def get_group_label(date_str):
date_obj = get_date_obj(date_str)
return get_date_group(date_obj)
# 读入数据
df = pd.read_csv('data.csv')
# 将日期字符串转换为日期对象并创建分组标签
df['date_obj'] = df['date'].apply(get_date_obj)
df['date_group'] = df['date'].apply(get_group_label)
# 按日期分组并统计数量
grouped = df.groupby('date_group').count()['id']
# 打印结果
print(grouped)
此代码将CSV中的日期字符串转换为日期对象,并使用“年-月”格式的标签将其分为组。然后,它对每个组中的项目数进行了计数,并将结果打印出来。