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

如何在pandas中插入缺失theta行并填充插值计算值?

解决Pandas DataFrame缺失theta步的填充问题

步骤1:创建原数据与完整theta序列

首先导入pandas并构造原始DataFrame,同时生成包含所有30度步进theta值的完整序列:

import pandas as pd

# 构造原始数据
df = pd.DataFrame({
    'index': [1,2,3,4,5,6,7,8,9],
    'name': ['wind']*9,
    'theta': [0,30,60,90,120,210,240,270,300],
    'r': [10,17,19,14,17,18,17,11,13]
}).set_index('index')

# 生成完整的theta序列(0到330,步长30)
full_thetas = pd.DataFrame({
    'theta': range(0, 360, 30),
    'name': ['wind']*12
})
full_thetas['index'] = range(1, 13)
full_thetas = full_thetas.set_index('index')

步骤2:合并数据补全缺失行

通过左连接将原始数据与完整theta序列合并,自动生成缺失theta对应的行,r列缺失值标记为NaN:

merged_df = full_thetas.merge(df[['theta', 'r']], on=['theta', 'name'], how='left')

步骤3:环形插值填充缺失值

由于theta是360度循环的(330的下一个有效角度是0),我们先复制首行到临时数据末尾,再用线性插值填充——等步长下线性插值等价于前后可用值的平均,完全符合需求:

# 复制首行到末尾,处理环形插值逻辑
temp_df = pd.concat([merged_df, merged_df.iloc[[0]]])
# 线性插值填充NaN
temp_df['r'] = temp_df['r'].interpolate(method='linear')
# 移除复制的首行,得到最终结果
final_df = temp_df.iloc[:-1]

最终结果

执行后final_df的输出与预期一致:

name  theta     r
index                  
1      wind      0  10.0
2      wind     30  17.0
3      wind     60  19.0
4      wind     90  14.0
5      wind    120  17.0
6      wind    150  17.5
7      wind    180  17.5
8      wind    210  18.0
9      wind    240  17.0
10     wind    270  11.0
11     wind    300  13.0
12     wind    330  11.5

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 09:33:12