Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.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 3.x 需要创建字符串变量,该变量具有年和周到日期时间格式的组合_Python 3.x_Pandas_Datetime_Indexing - Fatal编程技术网

Python 3.x 需要创建字符串变量,该变量具有年和周到日期时间格式的组合

Python 3.x 需要创建字符串变量,该变量具有年和周到日期时间格式的组合,python-3.x,pandas,datetime,indexing,Python 3.x,Pandas,Datetime,Indexing,它是一个字符串,前四位是年,后两位是周,我需要转换为datetime格式,作为年和周,并将该变量作为索引 它试过了 df1['period']=pd.to_datetime(df1['period'],格式=“%Y%U”) 它不起作用了也许你还需要一周中的某一天。您可以这样尝试: period 201801 201801 201801 201801 201801 输出: from datetime import datetime df1 = pd.DataFrame([['2017

它是一个字符串,前四位是年,后两位是周,我需要转换为datetime格式,作为年和周,并将该变量作为索引

它试过了
df1['period']=pd.to_datetime(df1['period'],格式=“%Y%U”)


它不起作用了

也许你还需要一周中的某一天。您可以这样尝试:

period 

201801

201801

201801

201801

201801
输出:

from datetime import datetime
df1 = pd.DataFrame([['201710', 2], ['201715', 3], ['201720', 4]], columns = ['period' ,'val'])
#Add Sunday as day of the week    
df1['period'] = df1['period'].astype(str) + '0'
df1['period'] = df1['period'].apply(lambda x: datetime.strptime(x, "%Y%W%w"))
df1.set_index('period', inplace=True)
print (df1)
或:

它有相同的输出

你可以试试这个

df1['period'] = df1['period'].astype(str) + '0'     
df1['period'] = pd.to_datetime(df1['period'], format='%Y%W%w')
df1.set_index('period', inplace=True)

什么具体不起作用?我看不出有任何错误。你能粘贴错误/异常吗?是的,尤其是第二个选项。您甚至可以将前两行组合成
df1['period']=pd.to_datetime(df1['period'].astype(str)+'0',format='%Y%W%W')
,但这可能只是太多代码的后遗症。@mostlyoxygen是的,我知道的诅咒:)
df1['period'] = df1['period'].astype(str) + '0'     
df1['period'] = pd.to_datetime(df1['period'], format='%Y%W%w')
df1.set_index('period', inplace=True)
sdf = pd.DataFrame(['201801','201801','201801','201802','201803'])
sdf['year'] = sdf[0].str[0:4]
sdf['week'] = sdf[0].str[5:7]
sdf['week'] = pd.to_numeric(sdf['week'])
df = pd.DataFrame({'year':sdf['year'], 'week':sdf['week']})
df