如何直接创建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
相关产品推荐
相关产品推荐

