如何将熊猫系列转换为时间序列?

2 投票
1 回答
3873 浏览
提问于 2025-04-18 13:05

我正在尝试从MYSQL服务器提取数据,并将其制作成一个数据框(dataframe)。我使用的SQL查询是

sql="""SELECT dp.Date, dp.Open , dp.High, dp.Low, dp.Close, dp.Volume, dp.Adj 
     FROM tickers AS tick
     INNER JOIN daily_price AS dp
     ON dp.ticker_id = tick.id
     WHERE tick.ticker = '%s'
     ORDER BY dp.Date ASC;"""%(ticker)
goog = psql.frame_query(sql, con=con, index_col='Date')

这个查询运行得很好,但当我使用函数 df=obtain_df(ticker)obtain_df 只是一个用来获取 dataframe 的函数)并且用 type(df['High']) 查看时,它显示的是 panda.series 而不是 timeseries。我不知道为什么。在我的SQL服务器中,日期的格式也是 'DATE'。

你能建议我怎么把这个系列转换成时间序列吗?

da['Date']=pd.DatetimeIndex(da['Date'])

da.set_index('Date')

print da.head()

我得到了以下输出enter image description here

我该如何将日期列设置为索引呢?

1 个回答

0

试试:

 df['Date'] = pd.DatetimeIndex(df['Date'])

或者:

 df['Date'] = pd.to_datetime(df['Date'])

如果你的 datetime 格式比较特殊:

 df['Date'] = pd.to_datetime(df['Date'], format="%d%m%Y")

撰写回答