簡體   English   中英

從8位日期,2,3和4位時間創建Pandas Datetime索引

[英]Create Pandas Datetime index from 8 digit date and 2,3, and 4 digit time

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

我想我將使用線程中的方法在其中放入類似df.index[i] = df.index.map(lambda t: t.replace(hour=hour, minute=minute, day=day))內容每個if語句。

這顯然行不通,而且我敢肯定這是非常低效的。 任何幫助表示贊賞。

謝謝。

好吧,只需將所有時間數字都填充為零,就可以確保代碼效率更高,從而避免了每次都要測試多長時間的需要。 我創建了一個名為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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM