【问题标题】:How to extract property of pandas index from string如何从字符串中提取熊猫索引的属性
【发布时间】:2021-07-28 08:00:18
【问题描述】:

我有一个问题,如何从 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 )
  • 非常感谢!像魅力一样工作!

标签: python pandas datetime indexing datetimeindex


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-07
    • 1970-01-01
    • 2023-03-08
    • 2020-09-06
    • 2014-10-03
    • 2018-05-24
    • 1970-01-01
    相关资源
    最近更新 更多