如何从字符串中提取 属性 of pandas 索引

How to extract property of pandas index from string

我有一个问题,如何从 pandas 中的字符串变量中提取索引 属性? 我想在循环中从日期时间索引中提取特定属性。 下面附上代码:

features_list = ['dayofweek',
             'dayofyear',
             'day',
             'year',
             'month',
             'daysinmonth',
             'is_leap_year',
             'is_month_end',
             'is_quarter_end',
             'is_year_end',
             'is_month_start',
             'is_quarter_start',
             'is_year_start',
             'quarter',
             'week']
for feat from features_list:
    dataset[f'{feat}'] = dataset.index.feat 

所以如果feat变量中的值为day,则字符串必须是'dataset.index.day'。 如果是星期,字符串必须是 'dataset.index.week'?

使用 eval 从字符串获取 属性。

dataset[f'{feat}'] = eval("dataset.index."+feat )