Python 将日期转换为月份
现在我有一张桌子:Python 将日期转换为月份,python,pandas,python-datetime,python-dateutil,Python,Pandas,Python Datetime,Python Dateutil,现在我有一张桌子: Score Customer ID my_dates Threshold Model_name is_alert 50 8 2017-08-05 50 Mod1 yes 50 9 2017-12-05 50 Mod1 yes 50 28 2017-05-22
Score Customer ID my_dates Threshold Model_name is_alert
50 8 2017-08-05 50 Mod1 yes
50 9 2017-12-05 50 Mod1 yes
50 28 2017-05-22 50 Mod2 yes
50 28 2017-05-26 50 Mod2 yes
50 36 2017-06-20 50 Mod2 yes
如果分数等于或超过阈值,is_警报将显示“是”
现在,我想将日期存储到以下格式中,并打印每个型号下每个存储箱中的警报数量,但如果一个客户在7天内多次收到警报,则只有第一次命中才会对总分作出贡献:
Model_name Jan-17 Feb-17 Mar-17 APR-17 May-17 Jun-17
Mod1
Mod2
有人能帮我吗?感谢与convert datetimes to month periods by、last convert to names of month by、before get difference per groups by一起使用,并过滤缺少值(每组第一行)且小于等于的行,如7
by和:
请提供您编写的代码。非常感谢。但我还需要检查这两个日期是否在7天之内,因此5月17日的Mod2应该是1。我不知道该怎么做?
df['my_dates'] = pd.to_datetime(df['my_dates'])
m = df['my_dates'].dt.to_period('m')
df['diff'] = df.groupby(['Model_name'])['my_dates'].diff().dt.days
print (df)
Score Customer ID my_dates Threshold Model_name is_alert diff
0 50 8 2017-08-05 50 Mod1 yes NaN
1 50 9 2017-12-05 50 Mod1 yes 122.0
2 50 28 2017-05-22 50 Mod2 yes NaN
3 50 28 2017-05-26 50 Mod2 yes 4.0
4 50 36 2017-06-20 50 Mod2 yes 25.0
df = df[df['diff'].ge(7) | df['diff'].isna()]
df1 = pd.crosstab(df['Model_name'], m)
df1.columns = df1.columns.strftime('%b-%y')
print (df1)
my_dates May-17 Jun-17 Aug-17 Dec-17
Model_name
Mod1 0 0 1 1
Mod2 1 1 0 0