问题:有了某年某月某日具体的时间和数值,要知道某月的平均值
df = pd.read_csv(file_path, sep='\t')
df['日期'] = pd.to_datetime(df['日期'], format='%Y%m')
df.set_index('日期', inplace=True)
#col月平均值
df_monthly_avg = df.groupby([df.index.year, df.index.month])['col'].mean()
#col月出现个数
df_monthly_count = df.groupby([df.index.year, df.index.month])['col'].count()
#重构df
df_monthly_avg = pd.concat([df_monthly_avg,df_monthly_count], axis=1)
#重命名列名
df_monthly_avg.columns = ['col改']
#构造时间
start_date = df.index.min().strftime('%Y-%m-01')
end_date = (df.index.max()).strftime('%Y-%m-31')
dates = pd.date_range(start=start_date, end=end_date, freq='M')
#把重构的时间索引付给重构的df
formatted_dates = dates.strftime("%Y-%m")
df_monthly_avg.index = formatted_dates
这样我们就得到了一个新的df,包含有我们月平均值的数据