【发布时间】:2020-03-26 04:15:40
【问题描述】:
我有几千行的数据框,其中包含地理、response_dates 和 True/False for in_compliance 列。
df = pd.DataFrame( {
"geography" : ["Baltimore", "Frederick", "Annapolis", "Hagerstown", "Rockville" , "Salisbury","Towson","Bowie"] ,
"response_date" : ["2018-03-31", "2018-03-30", "2018-03-28", "2018-03-28", "2018-04-02", "2018-03-30","2018-04-07","2018-04-02"],
"in_compliance" : [True, True, False, True, False, True, False, True]})
我想在 response_date 列中添加一列,表示最近四个日期的 True 值的数量,包括该行的 response_date。所需输出的示例:
geography response_date in_compliance Past_4_dates_sum_of_true
Baltimore 2018-03-24 True 1
Baltimore 2018-03-25 False 1
Baltimore 2018-03-26 False 1
Baltimore 2018-03-27 False 1
Baltimore 2018-03-30 False 0
Baltimore 2018-03-31 True 1
Baltimore 2018-04-01 True 2
Baltimore 2018-04-02 True 3
Baltimore 2018-04-03 False 3
Baltimore 2018-04-06 True 3
Baltimore 2018-04-07 True 3
Baltimore 2018-04-08 False 2
我尝试了不同的 groupby 和 rolling 方法。但我得到的结果不是我期望和需要的。
df.groupby('city').resample('d').sum().fillna(0).groupby('city').rolling(4,min_periods=1).sum()
这是我采取的另一种方法:
df1 = df.groupby(['city']).apply(lambda x: x.set_index('response_date').resample('1D').first())
df2 = df1.groupby(level=0)['in_compliance']\
.apply(lambda x: x.shift().rolling(min_periods=1,window=4).count())\
.reset_index(name='Past_4_dates_sum_of_true')
【问题讨论】:
标签: python pandas boolean pandas-groupby rolling-computation