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

Pandas中含NaN值的DataFrame行首尾非NaN列比值计算

解决方法

我们需要针对每行数据,定位第一个非NaN值的年份列和最后一个非NaN值的年份列,再计算两者的比值存入ratio列,具体实现如下:

1. 提取年份列

先从DataFrame中筛选出所有年份相关列(排除初始为空的ratio列):

year_cols = [2016, 2017, 2018, 2019]
year_data = z[year_cols]

2. 计算首尾非NaN值的比值

通过apply遍历每行,利用first_valid_index()和last_valid_index()获取首尾有效列名,提取对应值做除法(同时处理整行全NaN的特殊情况):

z['ratio'] = year_data.apply(
    lambda row: row[row.first_valid_index()] / row[row.last_valid_index()] 
    if row.first_valid_index() is not None and row.last_valid_index() is not None 
    else None,
    axis=1
)

完整可运行代码

import pandas as pd
import numpy as np

# 初始化原始DataFrame
z = pd.DataFrame({
    2016:[4.0,np.nan,6.0,7.0,np.nan],
    2017:[np.nan,0,5.0,0,np.nan],
    2018:[4.0,3,np.nan,3,1.0],
    2019:[2.0,np.nan,np.nan,np.nan,3.4],
    'ratio':''
})

# 提取年份列
year_cols = [2016, 2017, 2018, 2019]
year_data = z[year_cols]

# 计算ratio列
z['ratio'] = year_data.apply(
    lambda row: row[row.first_valid_index()] / row[row.last_valid_index()] 
    if row.first_valid_index() is not None and row.last_valid_index() is not None 
    else None,
    axis=1
)

# 查看结果
print(z)

结果验证

运行后ratio列的结果完全匹配需求:

  • 第一行:4.0 / 2.0 = 2.0
  • 第二行:0 / 3 = 0.0
  • 第三行:6.0 / 5.0 = 1.2
  • 第四行:7.0 / 3 ≈ 2.3333
  • 第五行:1.0 / 3.4 ≈ 0.2941

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 18:19:54