我有一个多数据框字典,其中索引设置为“日期”,但无法捕获搜索的特定日期。
根据链接创建的字典:
然后我尝试添加以下列为每一行创建特定的日期:
df_dict[k]['Day'] = pd.DatetimeIndex(df['Date']).day
它不工作。这个想法是只为每一行分隔一个月中的一天(从 1 到 31)。当我打电话给报告时,它会给我那次发生的月份。
如果需要,请提供更多详细信息。
问候和感谢!
我有一个多数据框字典,其中索引设置为“日期”,但无法捕获搜索的特定日期。
根据链接创建的字典:
然后我尝试添加以下列为每一行创建特定的日期:
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
# 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}}