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

如何无需重置索引为时间序列按位置添加含缺失值列

问题描述

我有一个DataFrame,希望从元组数组中提取值添加为新列,元组包含(位置, 值)信息。示例代码如下:

import pandas as pd
import numpy as np

alpha = [chr(i) for i in range(ord('A'), ord('K')+1)]

dt = pd.date_range(start='2025-1-1', freq='1h', periods = len(alpha))

df = pd.DataFrame ( alpha , index = dt )
df.index.name = 'timestamp'
df.columns = ['item']

c = np.array( [(1, 100), (2, 202), (6, 772)] )

目标是让第1行(对应item为B)的新列值为100,以此类推。我已通过以下代码实现需求:

df.reset_index(inplace = True) 
df.index.name = 'pos'

for x,y in c:
    df.loc[ int(x) , 'price'] = y

df.set_index("timestamp", inplace=True)

该方法虽能得到预期结果,但重置再重建索引的操作在多索引场景下较为繁琐。请问是否存在无需重置索引的更优方式,按位置添加含缺失值的列?

解决方案

可以直接利用pandas的位置定位特性或构造Series实现,完全不需要改动原索引:

方法1:通过iloc直接赋值

先初始化新列为缺失值,再遍历元组按行位置赋值:

# 先创建全为NaN的新列
df['price'] = np.nan
# 遍历元组数组,按整数行位置赋值
for pos, val in c:
    df.iloc[int(pos), df.columns.get_loc('price')] = val

iloc直接定位行的整数位置,df.columns.get_loc('price')确保赋值到正确的新列,全程无需修改原索引结构。

方法2:构造Series自动对齐

将元组数组转换成以位置为索引的Series,利用pandas的自动对齐机制完成赋值:

# 从元组构造Series,索引为行位置,值为对应价格
price_series = pd.Series({int(pos): val for pos, val in c}, dtype='float64')
# 按行位置匹配赋值,缺失位置自动填充NaN
df['price'] = price_series

这种方法无需循环,代码更简洁,pandas会自动将Series的索引(行位置)与DataFrame的行位置对应,未匹配到的位置自动填充缺失值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 23:10:06