【问题标题】:Create Pandas Datetime index from 8 digit date and 2,3, and 4 digit time从 8 位日期和 2,3 和 4 位时间创建 Pandas 日期时间索引
【发布时间】:2014-11-18 02:34:45
【问题描述】:

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 线程中的方法在每个if 语句中放入类似df.index[i] = df.index.map(lambda t: t.replace(hour=hour, minute=minute, day=day)) 的内容。

这显然行不通,而且我敢肯定效率极低。任何帮助表示赞赏。

谢谢。

【问题讨论】:

    标签: python datetime pandas


    【解决方案1】:

    您可以通过用零填充所有时间数字来确保您的代码更高效,从而避免每次测试时间的必要性。我创建了一个名为 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
    

    【讨论】:

      猜你喜欢
      • 2017-08-13
      • 1970-01-01
      • 1970-01-01
      • 2018-01-24
      • 2015-02-21
      • 1970-01-01
      • 2014-03-07
      • 2016-10-11
      • 1970-01-01
      相关资源
      最近更新 更多