我在 pandas 中有以下数据框
code time
1 003002
1 053003
1 060002
1 073001
1 073003
我想在 pandas 中生成以下数据框
code time new_time
1 003002 00:30:00
1 053003 05:30:00
1 060002 06:00:00
1 073001 07:30:00
1 073003 07:30:00
我用下面的代码来做
df['new_time'] = pd.to_datetime(df['time'] ,format='%H%M%S').dt.time
我怎样才能在熊猫中做到这一点?
Use Series.dt.floor http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.floor.html:
df['time'] = pd.to_datetime(df['time'], format='%H%M%S').dt.floor('T').dt.time
或者通过索引删除最后 2 个值,然后将格式更改为%H%M
:
df['time'] = pd.to_datetime(df['time'].str[:-2], format='%H%M').dt.time
print (df)
code time
0 1 00:30:00
1 1 05:30:00
2 1 06:00:00
3 1 07:30:00
4 1 07:30:00
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)