从8位数日期和2,3和4位数时间创建Pandas日期时间索引

时间:2014-11-18 02:34:46

标签: python datetime pandas

python / pandas以及stackoverflow的新手。目前正在使用Anaconda的Spyder 2.3.1。

我正在使用CSV数据集,该数据集提供如下日期和时间:

Date,Time
20140101,54
20140102,154
20140103,1654

我目前正在阅读日期并使用read_csv进行解析,如下所示:

df = pd.read_csv('filename.csv',                     
      index_col = 0,
      parse_dates= True, infer_datetime_format = True)

产生

Datetimeindex        Time
2014-01-01 00:00:00  54
2014-01-02 00:00:00  154
2014-01-03 00:00:00  1654

现在我需要将表格中每一行的时间戳替换为实际产生的时间:

Datetimeindex
2014-01-01 00:54:00
2014-01-02 01:54:00
2014-01-03 16:54:00

有人能提供一种有效的方法来实现这一结果吗?

到目前为止我的方法是:

import pandas as pd

length = len(df["Time"])
for i in range(0,length):
if len(str(df.iloc[i]["Time"]))==2:
    string = str(df.iloc[i]["Time"])
    hour = "00"
    minute = string
    second = "00"
    # replace time with actual time using hour, minute, and second variables
if len(str(df.iloc[i]["Time"])) == 3:
    string = str(df.iloc[i]["Time"])
    hour = "0" + string[:1]
    minute = string[1:]
    second = "00"
    # replace time with actual time using hour, minute, and second variables
if len(str(df.iloc[i]["Time"])) == 4:
    string = str(df.iloc[i]["Time"])
    hour = string[:2]
    minute = string[2:]
    second = "00"
    # replace time with actual time using hour, minute, and second variables

我想我会使用this线程中的方法在每个df.index[i] = df.index.map(lambda t: t.replace(hour=hour, minute=minute, day=day))语句中添加类似if的内容。

这显然不起作用,而且我确信效率非常低。任何帮助表示赞赏。

谢谢。

1 个答案:

答案 0 :(得分:0)

您可以通过用零填充所有时间数字来确保您的代码更高效,从而避免测试每次时间的必要性。我创建了一个名为time_test.csv的csv文件,然后将该数据作为字符串数据导入。我创建了一个空容器来放入日期时间,然后在DF上迭代,对于每一行,我根据需要使用while循环填充时间数据,然后将信息传递给datetime.datetime ....

import datetime
import pandas as pd
DF = pd.read_csv('time_test.csv', dtypes = {'Date' : str, 'Time' : str})
datetime_index = []

for row in DF.index:
    time_val = DF.loc[row, 'Time']
    date_val = DF.loc[row, 'Date']
    while len(time_val) != 4: #pad with zeros as needed to avoid conditional testing
        time_val = '0' + time_val
    datetime_index.append(datetime.datetime(int(date_val[:4]), int(date_val[4:6]), int(date_val[6:]), int(time_val[:2]), int(time_val[2:]), 00))

DF['Datetime'] = pd.Series(datetime_index, index = DF.index)

结果:

In [36]: DF
Out[36]:
       Date  Time            Datetime
0  20140101    54 2014-01-01 00:54:00
1  20140102   154 2014-01-02 01:54:00
2  20140103  1654 2014-01-03 16:54:00