1 回答

TA貢獻1829條經驗 獲得超7個贊
np.select(condition, choice,alternative) 在將日期強制轉換為日期時間并在中提取結束月份日期后使用yearmo
從 yearmo 中提取月末日期
df['startmo']=pd.to_datetime(df['yearmo'].astype(str), format='%Y%m')+ pd.offsets.MonthEnd(0)
脅迫strt_dt和end_dt約會
datedf['strt_dt'],df['end_dt']=pd.to_datetime(df['strt_dt']),pd.to_datetime(df['end_dt'])
提出條件
conditions=[df.startmo.dt.month==df.strt_dt.dt.month, df.startmo.dt.month==df.end_dt.dt.month]
#If month in yearmo is the same with strt_dt,substract strt_dt from endmont.
#If month in yearmo is the same with end_dt, extract the days in end_dt
提出對應于上述每個條件的選擇
choices=[df.startmo.sub(df.strt_dt).dt.days+1,df.end_dt.dt.day]
通過匹配條件和選擇來計算天數。也包括備選方案。這里的替代方案是開始和結束的月份與 yearmo 不匹配,這意味著月份在中間所以只需提取日期作為條件的替代方案
df['no_of days']=np.select(conditions,choices,df.startmo.dt.day)
ID Name strt_dt end_dt yearmo startmo no_of days
0 1 Jay 2019-04-22 2019-07-30 201904 2019-04-30 9
1 1 Jay 2019-04-22 2019-07-30 201905 2019-05-31 31
2 1 Jay 2019-04-22 2019-07-30 201906 2019-06-30 30
3 1 Jay 2019-04-22 2019-07-30 201907 2019-07-31 30
4 2 Fao 2019-07-14 2019-10-14 201907 2019-07-31 18
5 2 Fao 2019-07-14 2019-10-14 201908 2019-08-31 31
6 2 Fao 2019-07-14 2019-10-14 201909 2019-09-30 30
7 2 Fao 2019-07-14 2019-10-14 201910 2019-10-31 14
添加回答
舉報