2024-09-29 23:27:18 发布
网友
我基本上是python新手,我有以下要求 我有从一月到十二月的日期和一些时间的平均值,比如
在附图中有5行属于五月,6行属于六月
我们如何迭代和计算每个月的平均值,比如我想计算5月和6月的食物、饮料和消耗量的平均值(每个月我有12个月的数据)。你知道吗
我需要像这样的输出
Month Food Drink wastage May-17 2.0 3.0 2.0 June-17 2.5 2.5 3.0
import calendar df= pd.DataFrame({'date': ['6/8/2015','7/10/2018','6/5/2015'],'food':[1.5,2.5,3],'drinks':[2,2.4,3],'wastage':[2,2.5,3],}) df.date=pd.to_datetime(df.date,format="%m/%d/%Y") df=pd.DataFrame(df.groupby(by=[df.date.dt.month.rename('month'),df.date.dt.year.rename('year')]).mean()).reset_index() df['month'] = df['month'].apply(lambda x: calendar.month_abbr[x]) df['year']=df['year'].apply(str) df['year']=df.year.str.replace("20","") df['period'] = df[['month', 'year']].apply(lambda x: '-'.join(x), axis=1) df=df.drop(['year','month'],axis=1) df=df.rename(index=str, columns={"period": "month"}) cols = df.columns.tolist() cols = cols[-1:] + cols[:-1] df[cols]
输出
month drinks food wastage 0 Jun-15 2.5 2.25 2.5 1 Jul-18 2.4 2.50 2.5
首先把你的数据放到一个熊猫数据框里——我自己编的假数据——你需要弄清楚如何加载你的数据源。(来自csv或excel)。你知道吗
启动框架
import pandas as pd import datetime df1 = pd.DataFrame({'Start_date' : ['2018-01-01','2018-01-02','2018-01-03','2018-02- 01','2018-03-10','2018-02-05'],'food' : [2, 2.5, 3, 2.4, 5, 4],'drinks' : [1,2,3,4,5,6], 'wastage':[6,5,4,3,2,1]})
确保您的日期列上有日期格式-在这里,我的输入是字符串,所以我需要转换它(您需要在这里使用不同的格式)请参见(日期格式文档的底部:https://docs.python.org/2/library/datetime.html)
df1.Start_date = pd.to_datetime(df1.Start_date, format ='%Y-%m-%d')
我将添加一个月列: 编辑年份:
df1["period"] = df1.Start_date.apply(lambda x: datetime.datetime.strftime(x, '%b-%y')) df1['month'] = pd.DatetimeIndex(df1.Start_date).month
按平均值分组
df1.groupby(['month']).mean() # for only month groupings df1.groupby(['period']).mean() # for output listed above
输出
首先把你的数据放到一个熊猫数据框里——我自己编的假数据——你需要弄清楚如何加载你的数据源。(来自csv或excel)。你知道吗
启动框架
确保您的日期列上有日期格式-在这里,我的输入是字符串,所以我需要转换它(您需要在这里使用不同的格式)请参见(日期格式文档的底部:https://docs.python.org/2/library/datetime.html)
我将添加一个月列: 编辑年份:
按平均值分组
相关问题 更多 >
编程相关推荐