你好我希望转换一个&%;%Y%m%d%H%M'到日期时间并将其替换为数据帧字典。
import pandas as pd
import time
df1 = pd.DataFrame(data= {'col1':['201706202359' , '201706220510'], "col2" : ['0', '1']})
df2 = pd.DataFrame(data= {'col1':['201707202300' , '201706230600'],"col2" : ['0', '1']})
dfs = {'df1' : df1, 'df2' : df2}
for name, df in dfs.items():
for i in range(len(df)):
timestamp = time.strptime(str(df[["col1"]].iloc[i][0]), '%Y%m%d%H%M')
datetime = pd.to_datetime((str(timestamp[2])+"-"+str(timestamp[1])+"-"+str(timestamp[0])+" "+ str(timestamp[3])+":"+ str(timestamp[4])+":"+ str(timestamp[5])))
但是我无法替换转换后的col1
,col1
现在是{{1}}中的时间戳。
我怎么能这样做呢。
提前谢谢你。
答案 0 :(得分:2)
IIUC:
In [330]: for x in dfs:
...: dfs[x]['col1'] = pd.to_datetime(dfs[x]['col1'], format='%Y%m%d%H%M')
...:
In [331]: dfs
Out[331]:
{'df1': col1 col2
0 2017-06-20 23:59:00 0
1 2017-06-22 05:10:00 1, 'df2': col1 col2
0 2017-07-20 23:00:00 0
1 2017-06-23 06:00:00 1}
In [332]: dfs['df1']
Out[332]:
col1 col2
0 2017-06-20 23:59:00 0
1 2017-06-22 05:10:00 1
请注意,它也改变了原始DF:
In [340]: df1
Out[340]:
col1 col2
0 2017-06-20 23:59:00 0
1 2017-06-22 05:10:00 1
In [341]: df2
Out[341]:
col1 col2
0 2017-07-20 23:00:00 0
1 2017-06-23 06:00:00 1