如何在数据帧中将时间表示为int?

2024-06-06 19:22:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据帧,从CSV读取,例如(乘以HH:MM:SS):

    pta         ptd         tpl_num
4   05:17       05:18       0
6   05:29:30    05:30       1
9   05:42       05:44:30    2
11  05:53       05:54       3
12  06:03       06:05:30    4
17  06:24:30    NaN         5

dtypes

pta                object
ptd                object
tpl_num             int64

我正在尝试以int的形式获取ptaptd列,格式如下:

    pta      ptd      tpl_num
4   51700    51800    0
6   52930    53000    1
9   54200    54430    2
11  55300    55400    3
12  60300    60530    4
17  62430    NaN      5

看起来很简单-填充尾随的零,并将其转换为int。但我找不到一种方法。我已经转换为字符串,填充了零,去掉了冒号,但由于无法识别NaN单元格,因此无法转换为int。如果所有单元格中都没有:SS,我就无法转换为datetime。不知道该怎么办


Tags: csv数据objecthhnanssnum形式
3条回答

我假设您希望最终获得datetime对象

您可以创建一个helper函数来转换原始字符串,如:

import pandas as pd
import numpy as np
from datetime import datetime

col = pd.Series(['5:17', '05:30', np.NaN, '12:30:10'])

def date_converter(t):
    if pd.isna(t):
        return t
    if t.count(':')==2:
        return datetime.strptime(t, '%H:%M:%S')
    if t.count(':')==1:
        return datetime.strptime(t, '%H:%M')
    else:
        return None

col_converted = [date_converter(t) for t in col]

print(col_converted)

输出:

[datetime.datetime(1900, 1, 1, 5, 17), datetime.datetime(1900, 1, 1, 5, 30), nan, datetime.datetime(1900, 1, 1, 12, 30, 10)]

IIUC,你可以使用

final = df.assign(**pd.to_datetime(df[['pta','ptd']].stack()).dt.time.astype(str)
      .str.replace(':','').astype(int).unstack())

        pta      ptd  tpl_num
4   51700.0  51800.0        0
6   52930.0  53000.0        1
9   54200.0  54430.0        2
11  55300.0  55400.0        3
12  60300.0  60530.0        4
17  62430.0      NaN        5

以下是一个转换为十进制分钟的调整值,应适用于培训:

import pandas as pd
import numpy as np
from datetime import datetime

col = pd.Series(['5:17', '05:30', np.NaN, '12:30:10'])

def to_minutes(t):
    if pd.isna(t):
        return t
    if t.count(':')==2:
        t = [int(s) for s in t.split(':')]
        return 60*t[0] + t[1] + 1.0/60*t[2]
    if t.count(':')==1:
        t = [int(s) for s in t.split(':')]
        return 60*t[0] + t[1] 


col_converted = [to_minutes(t) for t in col]

print(col_converted)

输出:

[317, 330, nan, 750.1666666666666]

关于您的评论,您只想将scikit.learn转换为整数,您必须转换为一组通用单位。不能只将转换后的整数猛击在一起。如果您这样做,您已经将连续变量更改为有序变量,因为您已经破坏了线性。除非您想要有序变量,否则不要这样做。例如,如果我们看一个小时内10分钟的增量,你会得到如下结果:

from matplotlib import pyplot as plt

col = pd.Series(['5:00', '05:10', '5:20', '5:30', '5:40', '5:50', '6:00', '6:10', '6:20', 
    '6:30', '6:40', '6:50'])

def to_minutes(t):
    if pd.isna(t):
        return t
    if t.count(':')==2:
        t = [int(s) for s in t.split(':')]
        return 60*t[0] + t[1] + 1.0/60*t[2]
    if t.count(':')==1:
        t = [int(s) for s in t.split(':')]
        return 60*t[0] + t[1] 

def to_int(t):
    return int(t.replace(':',''))



true_mins = [to_minutes(t) for t in col]

skewed_time = [to_int(t) for t in col]
print(true_mins)
print(skewed_time)


plt.plot(true_mins, skewed_time)
plt.xlabel('actual minutes')
plt.ylabel('bogus time')
plt.show()

bogus time vs. actual time

相关问题 更多 >