使用info()时缺失日期列,如何转为datetime64[ns]存入DataFrame?
问题:将Yahoo Finance股票数据的日期索引转为DataFrame列并显示在info()中
问题描述
从Yahoo Finance获取MSFT股票数据后,直接查看时可见Date索引列:
Open High Low Close Volume Dividends Stock Splits Date 2015-01-02 00:00:00-05:00 40.724155 41.387470 40.619421 40.811432 27913900 0.0 0.0 2015-01-05 00:00:00-05:00 40.471039 40.785243 40.366306 40.436131 39673900 0.0 0.0 2015-01-06 00:00:00-05:00 40.479777 40.802706 39.746637 39.842644 36447900 0.0 0.0 2015-01-07 00:00:00-05:00 40.130662 40.549598 39.702999 40.348858 29114100 0.0 0.0 2015-01-08 00:00:00-05:00 40.802692 41.675477 40.776510 41.535831 29645200 0.0 0.0
但调用info()方法时,日期列不会出现在数据列列表中:
<class 'pandas.core.frame.DataFrame'> DatetimeIndex: 1257 entries, 2015-01-02 00:00:00-05:00 to 2019-12-30 00:00:00-05:00 Data columns (total 7 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 Open 1257 non-null float64 1 High 1257 non-null float64 2 Low 1257 non-null float64 3 Close 1257 non-null float64 4 Volume 1257 non-null int64 5 Dividends 1257 non-null float64 6 Stock Splits 1257 non-null float64 dtypes: float64(6), int64(1) memory usage: 110.9 KB
获取数据的代码如下:
company_name = "MSFT" company = tweets[tweets['ticker_symbol'] == company_name] company_stock = yf.Ticker(company_name).history(start=min(company.date).date(),end=max(company.date).date())
需求:将日期列转为datetime64[ns]类型并加入DataFrame,使其在info()中显示。
解决方案
方法1:使用reset_index()转换索引为列
reset_index()会将当前的DatetimeIndex转为普通数据列,并生成默认整数索引。处理后日期列会自动带有时区信息,可进一步移除时区转为纯datetime64[ns]类型:
# 将日期索引转为数据列 company_stock = company_stock.reset_index() # 移除时区,转为datetime64[ns] company_stock['Date'] = company_stock['Date'].dt.tz_localize(None)
执行后调用company_stock.info(),就能看到Date列出现在数据列列表中,dtype为datetime64[ns]。
方法2:手动添加日期列(保留原索引)
如果需要保留原DatetimeIndex,可手动将索引值作为新列添加到DataFrame:
# 添加日期列并移除时区 company_stock['Date'] = company_stock.index.tz_localize(None)
此方法下,原索引依然存在,新增的Date列会在info()中显示,类型为datetime64[ns]。
内容的提问来源于stack exchange,提问作者Deniz Turan
相关产品推荐
相关产品推荐

