我有一个像
这样的数据框Date Volume
9/23/2019 50
9/24/2019 234
9/25/2019 23124
9/26/2019 23412
9/27/2019 21213
9/30/2019 23241
10/1/2019 231323
10/2/2019 2312
10/3/2019 23213
10/4/2019 421020
10/7/2019 3212
10/8/2019 23122
import pandas as pd
i = input('enter credentials')
df = pd.read_csv('sample.csv')
我想计算两个条件下的平均值:
如果输入i为m,则计算月均值并按月显示结果,如果输入i为w,则计算周均值并按周显示结果。
>在这种情况下,可以有更多的数据帧,一周有 5 天,一个月有 20 天。
答案 0 :(得分:2)
您还没有向我们展示输出,但根据描述,您可以尝试将输入传递给此函数(可扩展):
首先将日期转换为实际的日期时间列:
df['Date'] = pd.to_datetime(df['Date'],format='%m/%d/%Y')
然后:
def myinp(i,dataframe,datecol):
freq_d = {'m':'m','w':'W'}
return dataframe.groupby(dataframe[datecol]
.dt.strftime(f"%{freq_d.get(i)}").rename(i)).mean()
print("By m: \n",myinp('m',df,'Date'))
print("---------------------------")
print("By w: \n",myinp('w',df,'Date'))
By m:
Volume
m
09 15212.333333
10 117367.000000
---------------------------
By w:
Volume
w
38 13606.6
39 140221.8
40 13167.0