Python 使用DataFrame索引日期创建日期列
我试图减少项目中创建各种日期列(工作日、工作日、日索引、周索引)过程中的代码膨胀,我想知道如何获取数据帧的索引并从索引中构建日期时间属性列 我想我可以访问Python 使用DataFrame索引日期创建日期列,python,pandas,Python,Pandas,我试图减少项目中创建各种日期列(工作日、工作日、日索引、周索引)过程中的代码膨胀,我想知道如何获取数据帧的索引并从索引中构建日期时间属性列 我想我可以访问.index或index.values,然后引用日期时间属性,如月,工作日,但索引似乎没有这些属性。我是否需要将索引值转换为新列表,然后根据该列表构建列 这是我的密码: historicals = pd.read_csv("2018-2019_sessions.csv", index_col="date", na_values=0) type(
.index
或index.values
,然后引用日期时间属性,如月
,工作日
,但索引
似乎没有这些属性。我是否需要将索引值转换为新列表,然后根据该列表构建列
这是我的密码:
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'
您的索引是字符串格式的。你
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
格式的,但版本相同。解决这个问题的唯一方法是转换为datetime。非常感谢。
date_col = pd.to_datetime(historicals.index)
print(date_col.weekday)