在创建各种日期列(工作日、工作日、日索引、周索引)的过程中,我试图减少项目中的代码膨胀,并且我想知道如何从索引中获取dataframe的索引并生成datetime属性列。
我想我可以访问.index或index.values,然后引用日期时间属性,如month、weekday等,但似乎Index没有这些属性。我是否需要将索引值转换为一个新列表,然后从该列表中构建列?
这是我的代码:
historicals = pd.read_csv("2018-2019_sessions.csv", index_col="date", na_values=0)
type(historicals)
// date formate = 2018-01-01, 2018-01-02, etc.
# Additional Date Fields
date_col = historicals.index
date_col.weekday
// AttributeError: 'Index' object has no attribute 'weekday'发布于 2019-12-05 21:40:51
索引采用字符串格式。你historicals.index可能长得像这样
print(historicals.index)
Index(['2018-01-01', '2018-01-02'], dtype='object')您需要将其转换为datetimeindex,并获取其weekday属性并将其赋值给新列。
historicals['weekday'] = pd.to_datetime(historicals.index).weekday或
date_col = pd.to_datetime(historicals.index)
print(date_col.weekday)https://stackoverflow.com/questions/59203566
复制相似问题