我正在探索熊猫 - 试图学习和应用它.目前我有一个csv文件,其中填充了以下结构的金融时间序列数据:
date, time, open, high, low, close, volume
2003.04.08,12:00,1.06830,1.06960,1.06670,1.06690,446
2003.04.08,13:00,1.06700,1.06810,1.06570,1.06630,433
2003.04.08,14:00,1.06650,1.06810,1.06510,1.06670,473
2003.04.08,15:00,1.06670,1.06890,1.06630,1.06850,556
2003.04.08,16:00,1.06840,1.07050,1.06610,1.06680,615
现在我想将csv数据转换为pandas DataFrame对象,以便日期和时间字段合并并成为DataFrame的DateTimeIndex,如下所示:
df = pa.read_csv(path,
names = ['date', 'time', 'open', 'high', 'low', 'close', 'vol'],
parse_dates = {'dateTime': ['date', 'time']},
index_col = 'dateTime')
Run Code Online (Sandbox Code Playgroud)
这可以产生一个很好的DataFrame对象:
<class 'pandas.core.frame.DataFrame'>
Index: 8676 entries, 2003.04.08 12:00 to nan nan
Data columns (total 5 columns):
open 8675 non-null values
high 8675 non-null values
low 8675 non-null values
close 8675 non-null values
vol 8675 non-null values
dtypes: float64(5)
Run Code Online (Sandbox Code Playgroud)
但经过检查,结果证明Index不是DataTimeIndex而是unicode字符串:
type(df.index)
>>> pandas.core.index.Index
df.index
>>> Index([u'2003.04.08 12:00', u'2003.04.08 13:00', u'2003.04.08 14:00', ....
Run Code Online (Sandbox Code Playgroud)
因此read_csv
解析了日期和时间字段,合并它们但没有创建DateTimeIndex.据我所知,文档中提供的日期时间对象列表的新数据结构对象应自动创建DateTimeIndex.我错了吗?DataFrame对象是异常吗?
我也尝试像这样转换当前索引:
df.index = pa.to_datetime(df.index)
Run Code Online (Sandbox Code Playgroud)
但是没有对索引进行任何更改,它仍然是unicode格式.我开始怀疑默认的解析函数没有完成它们的工作,但是我没有从它们那里收到任何错误消息.
在这种情况下如何在DateFrame中获得有效的DateTimeIndex?
解:
df = pa.read_csv(path,
names = ['date', 'time', 'open', 'high', 'low', 'close', 'vol'],
parse_dates={'datetime':['date','time']},
keep_date_col = True,
index_col='datetime'
)
Run Code Online (Sandbox Code Playgroud)
现在应用lambda函数,执行解析器应该做的事情:
df['datetime'] = df.apply(lambda row: datetime.datetime.strptime(row['date']+ ':' + row['time'], '%Y.%m.%d:%H:%M'), axis=1)
Run Code Online (Sandbox Code Playgroud)
Dateutil无法正确解析您的数据,但您可以在加载后执行此操作,使用strptime
:
import datetime
df['DateTime'] = df.apply(lambda row: datetime.datetime.strptime(row['date']+ ':' + row['time'], '%Y.%m.%d:%H:%M'), axis=1)
Run Code Online (Sandbox Code Playgroud)
这将产生'DateTime'列datetime64[ns]
,您可以将其用作索引
编辑
嗯..有趣的是,当我这样做时,它有效:
df = pd.read_csv(r'c:\data\temp.txt', parse_dates={'datetime':['date','time']}, index_col='datetime')
Run Code Online (Sandbox Code Playgroud)
你能看到当你从参数中删除列名时会发生什么 read_csv
归档时间: |
|
查看次数: |
14877 次 |
最近记录: |