python - 大熊猫过去 n 个日期的真实值总和
问题描述
我有一个几千行的数据框,其中包含地理、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')
解决方案
它更简单:
df['Past_4_dates_sum_of_true'] = df.rolling(4, min_periods=1)['in_compliance'].sum().astype(int)
输出:
geography response_date in_compliance Past_4_dates_sum_of_true
0 Baltimore 2018-03-24 True 1
1 Baltimore 2018-03-25 False 1
2 Baltimore 2018-03-26 False 1
3 Baltimore 2018-03-27 False 1
4 Baltimore 2018-03-30 False 0
5 Baltimore 2018-03-31 True 1
6 Baltimore 2018-04-01 True 2
7 Baltimore 2018-04-02 True 3
8 Baltimore 2018-04-03 False 3
9 Baltimore 2018-04-06 True 3
10 Baltimore 2018-04-07 True 3
11 Baltimore 2018-04-08 False 2
推荐阅读
- utf-8 - MTProto 字符串类型:长度是以字节还是 UTF-8 字符串长度来衡量的?
- c++ - 标识符未定义 C++
- azure - 删除 Azure Active Directory (ADD) 和关联门户
- flutter - 从飞镖列表中删除重复项
- javascript - 如何在本机反应中切换布尔值?
- algorithm - 如何处理整数平方根方法中的大输入?
- php - laravel 获取在受保护变量中建模的请求
- typescript - 如何制作具有对象价值的枚举?
- c# - 将 REST WebService 连接到 MySQL 数据库
- c++ - 调用 'Kt::Kt(int&, int)' 没有匹配的函数