我有一个现有的数据框,它看起来像: id start_date end_date0 1 20170601 202105311 2 20181001 202209302 3 20150101 201902283 4 20171101 20211031我正在尝试向此数据框添加 85 列,它们是:如果月/年(在 start_date 到 end_date 上循环)介于 20120101 和 20190101 之间:1其他:0我尝试了以下方法:start, end = [datetime.strptime(_, "%Y%m%d") for _ in ['20120101', '20190201']]global_list = list(OrderedDict(((start + timedelta(_)).strftime(r"%m/%y"), None) for _ in range((end - start).days)).keys())def get_count(contract_start_date, contract_end_date): start, end = [datetime.strptime(_, "%Y%m%d") for _ in [contract_start_date, contract_end_date]] current_list = list(OrderedDict(((start + timedelta(_)).strftime(r"%m/%y"), None) for _ in range((end - start).days)).keys()) temp_list = [] for each in global_list: if each in current_list: temp_list.append(1) else: temp_list.append(0) return pd.Series(temp_list)sample_df[global_list] = sample_df[['contract_start_date', 'contract_end_date']].apply(lambda x: get_count(*x), axis=1)示例 df 如下所示:customer_id contract_start_date contract_end_date 01/12 02/12 03/12 04/12 05/12 06/12 07/12 ... 04/18 05/18 06/18 07/18 08/18 09/18 10/18 11/18 12/18 01/191 1 20181001 20220930 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 1 1 1 19 2 20160701 20200731 0 0 0 0 0 0 0 ... 1 1 1 1 1 1 1 1 1 13 3 20171101 20211031 0 0 0 0 0 0 0 ... 1 1 1 1 1 1 1 1 1 13 rows × 88 columns它适用于小型数据集,但对于 160k 行,即使在 3 小时后也没有停止。有人可以告诉我更好的方法吗?当同一客户的日期重叠时面临问题。
添加回答
举报
0/150
提交
取消