4 回答
TA贡献1880条经验 获得超4个赞
用于isin检查每组的日期范围user以及agg.sum每组返回的布尔掩码
df['dt'] = pd.to_datetime(df['dt']) #if `dt` columns already in datetime dtype, ignore this
check_dates = pd.date_range('2015-12-31', '2016-01-10', freq='D')
s = df.groupby('user').dt.agg(lambda x: (~check_dates.isin(x)).sum())
Out[920]:
user
a 5
b 4
c 0
Name: dt, dtype: int64
TA贡献1951条经验 获得超3个赞
### Convert your dates to datetime
df['dt'] = pd.to_datetime(df['dt'], infer_datetime_format=True)
### Create the list of dates per user
user_days = df.groupby('user')['dt'].apply(list)
### Initialize the final dataframe
df_miss_dates = pd.DataFrame(user_days)
all_dates = pd.date_range('2015-12-31', '2016-01-10', freq='D')
### Find the number of missing dates per user
df_miss_dates['missing_days'] = df_miss_dates['dt'].apply(lambda x: len(set(all_dates) - set(x)))
df_miss_dates.drop(columns='dt', inplace=True)
print(df_miss_dates)
输出:
missing_days
user
a 5
b 4
c 0
TA贡献1831条经验 获得超9个赞
定义以下函数:
def missingDates(grp : pd.Series, d1 : pd.Timestamp, d2 : pd.Timestamp):
ndTotal = (d2 - d1).days + 1
ndPresent = grp[grp.between(d1, d2)].index.size
return ndTotal - ndPresent
然后将其应用到每个组并更改为 DataFrame (正如我从您的帖子中看到的,您只需要一个DataFrame,有 2 列):
result = df.groupby('user')['dt'].apply(missingDates,
pd.to_datetime('2015-12-31'), pd.to_datetime('2016-01-10'))\
.rename('missing_days').reset_index()
结果是:
user missing_days
0 a 5
1 b 4
2 c 0
我的解决方案依赖于这样一个事实:每个组中的日期都是唯一的,并且所有日期都没有时间部分。如果不满足这些条件,则应添加日期规范化和调用唯一 函数。
补充说明:将dt(列名)更改为其他名称,因为dt是Pandas中日期访问器的名称。用列名或变量名“覆盖”标准pandasonic名称是一种不好的做法。
TA贡献1833条经验 获得超4个赞
你可以这样做
from datetime import date, timedelta
sdate = date(2015, 12, 31) # start date
edate = date(2016, 1, 10) # end date
delta = edate - sdate # as timedelta
days=[]
for i in range(delta.days + 1):
day = sdate + timedelta(days=i)
days.append(str(day))
user=[]
missing_days = []
for user_n in df.user.unique():
user_days = df.loc[df.user ==user_n,'dt' ].to_list()
md = len([day for day in days if day not in user_days])
user.append(user_n)
missing_days.append(md)
new_df = pd.DataFrame({'user': user,'missing_days': missing_days})
new_df
输出
user missing_days
a 5
b 4
添加回答
举报