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

Pandas:根据lof列值将normalized flux列替换为np.nan

问题与解决方案

问题描述

我有一个如下所示的DataFrame:

wavelength  normalized flux  lof
0       5100.00        0.948305    1
1       5100.07        0.796783    1
2       5100.14        0.696425    1
3       5100.21        0.880586    1
4       5100.28        0.836257    1
...         ...             ...  ...
4281    5399.67        1.076449    1
4282    5399.74        1.038198    1
4283    5399.81        1.004292    1
4284    5399.88        0.946977    1
4285    5399.95        0.894559    1

需求:当lof列的值为-1时,将normalized flux列对应的值替换为np.nan;否则保持原值不变。

简便实现方法

方法1:使用np.where

直观的向量式操作,一行代码即可完成:

import numpy as np
import pandas as pd

# 假设你的DataFrame名为df
df['normalized flux'] = np.where(df['lof'] == -1, np.nan, df['normalized flux'])

方法2:使用Pandas的loc索引

通过布尔索引定位目标行后直接赋值,性能高效:

df.loc[df['lof'] == -1, 'normalized flux'] = np.nan

方法3:使用mask方法

mask方法语义贴合需求,会在条件为真时替换对应值:

df['normalized flux'] = df['normalized flux'].mask(df['lof'] == -1, np.nan)

以上三种方法都简洁高效,其中loc方法在处理大规模数据集时表现更优,mask方法的可读性更强。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 08:05:26