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

如何直接创建col_list列:仅记录fruit和clothes非空的字段名

实现方案

可以直接用 Pandas 的 apply 方法结合列表推导快速实现需求,代码如下:

import pandas as pd
import numpy as np

# 指定需要检查的目标列
target_cols = ['fruit', 'clothes']

# 生成col_list列
df['col_list'] = df[target_cols].apply(
    lambda row: [col for col in target_cols if pd.notna(row[col])] or np.nan,
    axis=1
)

代码说明

  • 先定义要检查的字段集合 target_cols;
  • 通过 apply(axis=1) 逐行处理数据:遍历目标列,筛选出当前行非空的列名;
  • 如果筛选结果为空(即两个字段都为空),则赋值为 np.nan,否则返回列名列表。

执行后得到的结果如下:

fruit  clothes trending          col_list
0  apple    shirt       no  [fruit, clothes]
1    NaN  trouser      yes         [clothes]
2    NaN      NaN      yes               NaN

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 18:15:50