Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用DataFrame索引日期创建日期列_Python_Pandas - Fatal编程技术网

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)