You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将OHLC数据收盘价转为以timestamp为索引的Series时出现NaN问题

问题描述

我有一个包含OHLC数据的DataFrame,需要将收盘价转换为以timestamp列为索引的Pandas Series。

从SQLite数据库读取数据的代码如下:

conn = sql.connect('allStockData.db') 
price = pd.read_sql_query("SELECT * from ohlc_minutes", conn)
price['timestamp'] = pd.to_datetime(price['timestamp'])

DataFrame的输出示例(部分数据):

timestamp  open   high   low  close  volume  trade_count      vwap symbol  volume_10_day
0     2022-09-16 08:00:00+00:00  3.19  3.570  3.19  3.350   66475          458  3.404240   AAOI            NaN
1     2022-09-16 08:05:00+00:00  3.35  3.440  3.33  3.430   28925          298  3.381131   AAOI            NaN
...
8763  2022-09-08 23:55:00+00:00  1.36  1.360  1.33  1.340   21394           32  1.348223   RUBY       515994.5

当尝试用以下代码转换时,返回结果全为NaN:

price = pd.Series(price['close'], index=price['timestamp'])

但去掉index参数后,能正常获取收盘价数据:

price = pd.Series(price['close'])

请问如何正确将收盘价列转换为以timestamp列为索引的Pandas Series?


解决方案

出现全NaN的核心原因是:price['close']本身带有原DataFrame的整数索引,使用pd.Series(..., index=price['timestamp'])时,Pandas会尝试将新的timestamp索引与原Series的整数索引对齐,因两者无法匹配,最终返回全NaN。

以下是几种可行的解决方法:

方法1:先设置DataFrame索引再提取Series

将timestamp设为DataFrame的索引,再直接提取close列即可得到目标Series:

# 修改原DataFrame
price.set_index('timestamp', inplace=True)
close_series = price['close']

# 不修改原DataFrame的写法
close_series = price.set_index('timestamp')['close']

方法2:重置收盘价Series的索引

先提取close列,再用set_index替换索引为timestamp:

close_series = price['close'].set_index(price['timestamp'])

方法3:直接传入数值数组绕过索引对齐

使用values属性获取收盘价的原始数值数组,避免原索引的干扰:

close_series = pd.Series(price['close'].values, index=price['timestamp'])

内容的提问来源于stack exchange,提问作者a7dc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 21:22:02