将Pandas列转换为小时和分钟

3
我有一个Pandas DataFrame中的字段是整数格式。如何将其转换为DateTime格式并将该列附加到我的DataFrame?具体来说,我需要小时和分钟。
例如:
  • DataFrame名称:df
  • 作为列表的列:df.index
  • dtype='int64'
  • df.index中的示例数据 -- [0, 15, 30, 45, 100, 115, 130, 145, 200...2300, 2315, 2330, 2345]

我尝试了 pd.to_datetime(df.index, format='') 但它返回的格式是错误的。

3个回答

2

您有一个索引,其中包含以HHMM表示的时间值,其为整数。要将其转换为datetime数据类型,您必须首先创建可以被to_datetime()方法正确转换的字符串。

time_strs = df.index.astype(str).str.zfill(4)

这将把所有整数值转换为字符串,并在左侧填充零以达到4个字符的长度,例如15将变成字符串"0015"

现在您可以使用格式"%H%M"将其转换为日期时间对象:

pd.to_datetime(time_strs, format="%H%M")

然后使用datetime对象的方法来访问小时和分钟。

哇!太棒了!非常感谢。 - king_python

2
import pandas as pd
    df = pd.DataFrame({'time':[0, 15, 30, 45, 100, 115, 130, 145, 200, 2300, 2315, 2330, 2345]})

df.set_index('time', inplace=True)

df['datetime_dtype'] = pd.to_datetime(df.index, format='%H', exact=False)

df['str_dtype'] = df['datetime_dtype'].astype(str).str[11:16]

print(df)


datetime_dtype  str_dtype
time        
0   1900-01-01 00:00:00 00:00
15  1900-01-01 15:00:00 15:00
30  1900-01-01 03:00:00 03:00
45  1900-01-01 04:00:00 04:00
100 1900-01-01 10:00:00 10:00
115 1900-01-01 11:00:00 11:00
130 1900-01-01 13:00:00 13:00
145 1900-01-01 14:00:00 14:00
200 1900-01-01 20:00:00 20:00
2300    1900-01-01 23:00:00 23:00
2315    1900-01-01 23:00:00 23:00
2330    1900-01-01 23:00:00 23:00
2345    1900-01-01 23:00:00 23:00

print(df.dtypes)

datetime_dtype    datetime64[ns]
str_dtype                 object
dtype: object

如果您想回到今年,可以使用时间差。

delta = pd.Timedelta(weeks=6278, hours=0, minutes=0)
df['datetime_dtype_2020'] = df['datetime_dtype'] + delta

print(df)

    datetime_dtype  str_dtype   datetime_dtype_2020
time            
0   1900-01-01 00:00:00 00:00   2020-04-27 00:00:00
15  1900-01-01 15:00:00 15:00   2020-04-27 15:00:00
30  1900-01-01 03:00:00 03:00   2020-04-27 03:00:00
45  1900-01-01 04:00:00 04:00   2020-04-27 04:00:00
100 1900-01-01 10:00:00 10:00   2020-04-27 10:00:00
115 1900-01-01 11:00:00 11:00   2020-04-27 11:00:00
130 1900-01-01 13:00:00 13:00   2020-04-27 13:00:00
145 1900-01-01 14:00:00 14:00   2020-04-27 14:00:00
200 1900-01-01 20:00:00 20:00   2020-04-27 20:00:00
2300    1900-01-01 23:00:00 23:00   2020-04-27 23:00:00
2315    1900-01-01 23:00:00 23:00   2020-04-27 23:00:00
2330    1900-01-01 23:00:00 23:00   2020-04-27 23:00:00
2345    1900-01-01 23:00:00 23:00   2020-04-27 23:00:00

1
如果你只需要小时和分钟,那么可以使用datetime.time对象。
import datetime

def int_to_time(i):
    if i < 60:
        return datetime.time(0, i)
    elif i < 1000:
        return datetime.time(int(str(i)[0]), int(str(i)[1:]))
    else:
        return datetime.time(int(str(i)[0:2]), int(str(i)[2:]))

df.index.apply(int_to_time)

例子
import datetime
import numpy as np

ints = [i for i in np.random.randint(0, 2400, 100) if i % 100 < 60][0:5]
df = pd.DataFrame({'a': ints})

>>>df
0  1559
1  1712
2  1233
3   953
4   938

>>>df['a'].apply(int_to_time)
0    15:59:00
1    17:12:00
2    12:33:00
3    09:53:00
4    09:38:00

从那里,您可以访问值的hourminute属性。

>>>df['a'].apply(int_to_time).apply(lambda x: (x.hour, x.minute))
0    (15, 59)
1    (17, 12)
2    (12, 33)
3     (9, 53)
4     (9, 38)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接