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

如何在Pandas DataFrame行中提取非NaN初始/最终价格并计算差价?

解决DataFrame每行提取首尾非NaN价格并计算差价的问题

问题背景

我们有一份包含四种苹果年度价格的DataFrame,部分年份价格以NaN缺失,需要实现:

  • 为每行提取第一个非NaN价格作为Price_Initial
  • 提取最后一个非NaN价格作为Price_Final
  • 计算两者差价Price_Gap(Price_Initial - Price_Final)

原始DataFrame代码:

import pandas as pd
import numpy as np

a = {'Price_Y19':[np.nan,np.nan,np.nan,10],
     'Price_Y20':[np.nan,np.nan,10,9],
     'Price_Y21':[np.nan,10,9,8],
     'Price_Y22':[10,9,8,7]}

index_name = ['yellow apple','red apple','white apple','gray apple']

df = pd.DataFrame(data = a,
                  index = index_name)

目标DataFrame效果:

b = {'Price_Y19':[np.nan,np.nan,np.nan,10],
     'Price_Y20':[np.nan,np.nan,10,9],
     'Price_Y21':[np.nan,10,9,8],
     'Price_Y22':[10,9,8,7],
     'Price_Initial':[10,10,10,10],
     'Price_Final':[10,9,8,7],
     'Price_Gap':[0,1,2,3]}

df1 = pd.DataFrame(data = b,
                  index = index_name)

解决方案代码

直接在原始DataFrame上添加新列即可,完整代码如下:

import pandas as pd
import numpy as np

# 原始DataFrame构造
a = {'Price_Y19':[np.nan,np.nan,np.nan,10],
     'Price_Y20':[np.nan,np.nan,10,9],
     'Price_Y21':[np.nan,10,9,8],
     'Price_Y22':[10,9,8,7]}
index_name = ['yellow apple','red apple','white apple','gray apple']
df = pd.DataFrame(data=a, index=index_name)

# 提取第一个非NaN价格作为Price_Initial
df['Price_Initial'] = df.apply(lambda row: row.dropna().iloc[0], axis=1)
# 提取最后一个非NaN价格作为Price_Final
df['Price_Final'] = df.apply(lambda row: row.dropna().iloc[-1], axis=1)
# 计算差价
df['Price_Gap'] = df['Price_Initial'] - df['Price_Final']

print(df)

代码解释

  • 提取Price_Initial:使用df.apply(..., axis=1)遍历每一行,对每行执行row.dropna()去掉所有NaN值,再用iloc[0]取第一个剩余值。
  • 提取Price_Final:逻辑类似,用iloc[-1]取每行去掉NaN后的最后一个值。
  • 计算Price_Gap:直接用Price_Initial减去Price_Final,得到差价。

执行后输出的DataFrame将完全匹配目标效果。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 12:25:28