【发布时间】: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)) 的内容。
这显然行不通,而且我敢肯定效率极低。任何帮助表示赞赏。
谢谢。
【问题讨论】: