我有一个问题,如何从 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'?
答案 0 :(得分:0)
使用 eval 从字符串到属性。
dataset[f'{feat}'] = eval("dataset.index."+feat )