Skip to main content
 首页 » 编程设计

python之有条件地创建新的数据框列以显示现有列的内容

2025年05月04日16cloudgamer

我有一个 pandas 数据框,它如下所示

SKU  ClosingBalance 
S1       10 
S2       np.nan 
S3       0 
S4       20 

我想创建一个新列,它将仅显示具有正期末余额的 SKU,其余的应标记为 np.nan,如下所示

SKU      ClosingBalance    SKU_CB 
S1       10                S1 
S2       np.nan            np.nan 
S3       0                 np.nan 
S4       20                S4 

我试过了

conditions = [(df['ClosingBalance'] > 1)] 
df['SKU_CB'] = np.select(conditions, df['SKU'], default=np.nan) 

不工作。需要您的帮助。

请您参考如下方法:

您可以使用 np.where 来做到这一点:

df['SKU_CB'] = np.where(df['ClosingBalance'] > 1, df['SKU'], np.nan) 

或者,在您使用 np.select 时,你似乎对第二个参数有问题:

choicelist : list of ndarrays The list of arrays from which the output elements are taken. It has to be of the same length as condlist.

应该是这样

df['SKU_CB'] = np.select(conditions, [df['SKU']], default=np.nan)