如何高效实现支持各单元格自定义输入的Pandas DataFrame日历
优化资产日历构建逻辑的需求
现有资产列表assets = ['1', '2', '3', ..., 'n'],每个资产在指定日期范围date_range = ['2023-01-01', '2023-01-02', ..., '202x-xx-xx']内的每个日期都对应唯一输入。目前已有实现代码,但逻辑既不合理也不高效,希望大家提供优化思路或解决方案。我已经开始尝试用pd.date_range寻找替代方案。
当前实现代码
# list of assets assets = ['A1','A2','A3','A4'] # Dataframe with data that will be used to build the calendar and be the reference for inputs data = {'PRODUCT': ['A1', 'B1', 'C1', 'D1'], 'DATE': [2023-01-02, 2023-07-15, 2023-12-21]} df_data = pd.DataFrame(data) # Building the columns of the calendar today = pd.Timestamp(2023, 1, 1) today_str = str(today) columns = list() columns.append('ASSETS') date_max = df_data['DATE'].max() delta = (date_max - today).days # 注:原代码此处误写为data_max,应为date_max for i in range(0, delta+1): columns.append(str((today+timedelta(days=i)).date())) # Building the calendar and using the assets as index df_calendar = pd.DataFrame(columns = columns) df_calendar['ASSETS'] = assets df_calendar.index = list(df_calendar['ASSETS']) df_calendar= df_calendar.drop('ASSETS', axis=1) df_calendar= df_calendar.fillna(0)
当前生成结果
| index | 2023-01-01 | 2023-01-02 | .......... | 2023-12-21 |
|---|---|---|---|---|
| A1 | 0 | 0 | . | 0 |
| A2 | 0 | 0 | . | 0 |
| A3 | 0 | 0 | . | 0 |
| A4 | 0 | 0 | . | 0 |
内容的提问来源于stack exchange,提问作者Douglas Mateus Machado
相关产品推荐
相关产品推荐

