即使日期列设置为索引,日期也不起作用

问题描述

我有一个多数据框字典,其中的索引设置为“日期”,但在捕获特定搜索日期时遇到了麻烦。

链接创建的字典:

Call a report from a dictionary of dataframes

然后,我尝试添加以下列以为每一行创建特定的日期:

df_dict[k]['Day'] = pd.DatetimeIndex(df['Date']).day

它不起作用。想法是为每一行仅分隔月份中的某天(从1到31)。当我打电话给报告时,它将给我该事件发生的月份。

更多详细信息(如果需要)。

致谢,谢谢!

解决方法

  • 对于您的代码,没有'Date'列,因为它被设置为索引。
    • df_dict = {f.stem: pd.read_csv(f,parse_dates=['Date'],index_col='Date') for f in files}
  • 要从索引中提取day,请使用以下代码。
    • df_dict[k]['Day'] = df.index.day
  • 从此question
  • 中提取代码
# here you can see the Date column is set as the index
df_dict = {f.stem: pd.read_csv(f,index_col='Date') for f in files}

data_dict = dict()  # create an empty dict here
for k,df in df_dict.items():
    df_dict[k]['Return %'] = df.iloc[:,0].pct_change(-1)*100

    # create a day column; this may not be needed
    df_dict[k]['Day'] = df.index.day 

    # aggregate the max and min of Return
    mm = df_dict[k]['Return %'].agg(['max','min']) 

    # get the min and max day of the month
    date_max = df.Day[df['Return %'] == mm.max()].values[0]
    date_min = df.Day[df['Return %'] == mm.min()].values[0]
    
    # add it to the dict,with ticker as the key
    data_dict[k] = {'max': mm.max(),'min': mm.min(),'max_day': date_max,'min_day': date_min}

# print(data_dict)
[out]:
{'aapl': {'max': 8.702843218147871,'max_day': 2,'min': -4.900700398891522,'min_day': 20},'msft': {'max': 6.603769278967109,'min': -4.084428935702855,'min_day': 8}}