gpt4 book ai didi

python - 按日期范围对数据框进行子集化

转载 作者:行者123 更新时间:2023-12-01 07:42:07 26 4
gpt4 key购买 nike

尝试以有效的方式按日期范围分隔数据框,到目前为止我只提出:

mask0 = df['Date of survey'].between('2010-01-01', '2010-12-31')
mask1 = df['Date of survey'].between('2011-01-01', '2011-12-31')
mask2 = df['Date of survey'].between('2012-01-01', '2012-12-31')

...
maskn = df['Date of survey'].between('nnnn-01-01', 'nnnn-12-31')

任何想法将不胜感激!(我将使用掩码对数据帧进行子集化,并获取每年每个列变量的平均和)。

最佳答案

这里更好的是使用 DataFrame.resample使用 meansum 等聚合函数按年计算:

df1 = df.resample('A', on='Date of survey').agg(['mean','sum'])

或者使用DataFrame.groupby按年 Series.dt.year :

df2 = df.groupby(df['Date of survey'].dt.year).agg(['mean','sum'])

关于python - 按日期范围对数据框进行子集化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56645084/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com