【问题标题】:Date is not working even when date column is set to index即使日期列设置为索引,日期也不起作用
【发布时间】:2023-03-27 15:08:01
【问题描述】:

我有一个多数据框字典,其中索引设置为“日期”,但无法捕获搜索的特定日期。

根据链接创建的字典:

Call a report from a dictionary of dataframes

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

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

它不工作。这个想法是只为每一行分隔一个月中的一天(从 1 到 31)。当我调用报告时,它会告诉我发生该事件的月份。

如果需要,请提供更多详细信息。

问候和感谢!

【问题讨论】:

    标签: pandas date indexing dayofmonth


    【解决方案1】:
    • 在您的代码中,没有'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, parse_dates=['Date'], 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,
              'max_day': 2,
              'min': -4.084428935702855,
              'min_day': 8}}
    

    【讨论】:

    • 再次正常工作。我刚刚添加了结尾以创建一个新的数据框,以便于阅读复制原始代码的结尾。非常感谢您的善意和帮助!
    猜你喜欢
    • 1970-01-01
    • 2016-10-03
    • 2020-11-21
    • 2011-04-30
    • 1970-01-01
    • 2020-05-27
    • 1970-01-01
    • 2018-01-24
    • 2017-04-05
    相关资源
    最近更新 更多