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

Pandas数据处理求助:UPOR为0/NaN时用NPOR计算Qnd列

Solution for Conditional Column Calculation in Pandas

Hey there! Let's sort out your Qnd column calculation. The goal is to use UPOR when it's not 0 or NaN, and fall back to NPOR whenever those invalid cases pop up. Here are a few straightforward, efficient ways to do this:

Method 1: Use numpy.where (Intuitive Conditional Check)

This is great for explicit, easy-to-read conditional logic:

import numpy as np

# Check if UPOR is 0 or NaN; use NPOR in those cases, else UPOR
GU_ES3['Qnd'] = GU_ES3['Qnd,hw_m2'] * np.where(
    (GU_ES3['UPOR'] == 0) | GU_ES3['UPOR'].isna(),
    GU_ES3['NPOR'],
    GU_ES3['UPOR']
)

The np.where function evaluates the condition for every row: if the condition is True (UPOR is 0 or missing), it uses the NPOR value; otherwise, it sticks with UPOR.

Method 2: Pandas where (Cleaner Pandas-Native Approach)

Pandas has its own where method (note: it inverts the condition compared to numpy.where):

# Define when UPOR is valid (not NaN and not 0)
valid_upor = GU_ES3['UPOR'].notna() & (GU_ES3['UPOR'] != 0)

# Keep UPOR where valid, replace with NPOR otherwise
GU_ES3['Qnd'] = GU_ES3['Qnd,hw_m2'] * GU_ES3['UPOR'].where(valid_upor, GU_ES3['NPOR'])

This approach keeps your code focused on the "valid" case first, which can make logic easier to follow for complex conditions.

Method 3: replace + fillna (Concise One-Liner)

If you prefer a more compact solution, convert 0s to NaNs first, then fill all NaNs with NPOR:

import numpy as np

GU_ES3['Qnd'] = GU_ES3['Qnd,hw_m2'] * GU_ES3['UPOR'].replace(0, np.nan).fillna(GU_ES3['NPOR'])

This works because replace(0, np.nan) turns all 0 values into missing values, then fillna(GU_ES3['NPOR']) replaces every NaN (original or converted) with the corresponding NPOR value.

All three methods will give you the same result—pick the one that fits your coding style best!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:43:47