熊猫数据框在日期时间之前添加零填充

时间:2018-06-28 20:11:35

标签: python pandas

我正在使用Pandas数据框。我有一个dataFrame df如下:

time      id
-------------
5:13:40    1
16:20:59   2
...

对于第一行,时间5:13:40之前没有零填充,我想将其转换为05:13:40。因此,我期望的df将是:

time       id
-------------
05:13:40    1
16:20:59    2
...

time的类型为<class 'datetime.timedelta'>。有人可以给我一些提示来解决这个问题吗?非常感谢!

1 个答案:

答案 0 :(得分:1)

使用pd.to_timedelta

df['time'] = pd.to_timedelta(df['time'])

之前:

print(df)

       time   id
1   5:13:40  1.0
2  16:20:59  2.0

df.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 2 entries, 1 to 2
Data columns (total 2 columns):
time    2 non-null object
id      2 non-null float64
dtypes: float64(1), object(1)
memory usage: 48.0+ bytes

之后:

print(df)

      time   id
1 05:13:40  1.0
2 16:20:59  2.0

df.info()
d<class 'pandas.core.frame.DataFrame'>
Int64Index: 2 entries, 1 to 2
Data columns (total 2 columns):
time    2 non-null timedelta64[ns]
id      2 non-null float64
dtypes: float64(1), timedelta64[ns](1)
memory usage: 48.0 bytes