从numpy loadtxt()获取日期列 [英] Get date column from numpy loadtxt()
本文介绍了从numpy loadtxt()获取日期列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含下表的文本文件.
I have a text file which contains following table.
Day Month Year Avg Power
01 01 2000 30
02 01 2000 41
04 01 2000 55
05 01 2000 78
06 01 2000 134
07 01 2000 42
我想将日",月"和年"列加载到单个datetime值中.为此,请按照以下步骤操作.但是代码无法按我期望的那样工作.
I want to load the Day,month and year columns into single datetime value. To do that followed following steps. But the code doesn't work what I expect.
from numpy import loadtxt
import datetime
def date_converter(x,y,z):
date = "{},{},{}".format(x,y,z)
return datetime.datetime.strptime(date,r"%d,%m,%Y")
data3 = loadtxt('complex_data_file.txt',dtype=int, usecols=(0,1,2,4),
converters={(0,1,2):date_converter,3:int})
要达到我的要求我该怎么做?
What I have to do to achieve my requirement?
推荐答案
我将Pandas模块用于此任务:
I'd use Pandas module for this task:
In [228]: df = pd.read_csv(fn, usecols=[0,1,2,4], parse_dates={'Date':[2,1,0]})
In [229]: df
Out[229]:
Date Avg Power
0 2000-01-01 30
1 2000-01-02 41
2 2000-01-04 55
3 2000-01-05 78
4 2000-01-06 134
5 2000-01-07 42
In [230]: df.dtypes
Out[230]:
Date datetime64[ns]
Avg Power int64
dtype: object
将其转换为Numpy数组也很容易:
it's also very easy to convert it to a Numpy array:
In [231]: df.values
Out[231]:
array([[Timestamp('2000-01-01 00:00:00'), 30],
[Timestamp('2000-01-02 00:00:00'), 41],
[Timestamp('2000-01-04 00:00:00'), 55],
[Timestamp('2000-01-05 00:00:00'), 78],
[Timestamp('2000-01-06 00:00:00'), 134],
[Timestamp('2000-01-07 00:00:00'), 42]], dtype=object)
这篇关于从numpy loadtxt()获取日期列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文