[英]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.