Skip to main content
 首页 » 编程设计

python之如何根据给定的标准填写一些字段

2025年05月04日14mq0036

df: 
NEW  COL1  COL2 
1    2     9 
3    NaN   NaN 
0    7     NaN 
 
column_names = [COL1,COL2] 

我想将 TOTAL 的值设置为等于 NEW,只有当 NEW > 0 并且一行中 COL1 和 COL2 的总和等于 0 时。

我是这样做的,但结果不正确(即 COL1 在相应行中等于 0)。例如,在第二行中,COL1 需要等于 3,但它等于 0。

df[column_names] = df[column_names].fillna(0) 
df.COL1.where((df.NEW>0 & (df[column_names].sum(axis=1) == 0)),df.NEW) 

请您参考如下方法:

您可以将 DataFrame.apply 与 axis=1 一起使用(将函数应用于每一行),并在该函数中执行您的逻辑。示例 -

df['TOTAL'] = df.apply((lambda row: row[col_names].sum() or row['NEW']), axis=1) 

演示 -

In [12]: df 
Out[12]: 
   NEW  COL1  COL2 
0    1     2     9 
1    3   NaN   NaN 
2    0     7   NaN 
 
In [13]: df['TOTAL'] = df.apply((lambda row: row[col_names].sum() or row['NEW']), axis=1) 
 
In [14]: df 
Out[14]: 
   NEW  COL1  COL2  Total 
0    1     2     9     11 
1    3   NaN   NaN      3 
2    0     7   NaN      7 

您的 Series.where 问题方法是 Series.where 如果条件为真则返回 Col1 的值,否则返回 NEW 的值。因此,这将仅在满足条件的情况下返回 NEW 值(这实际上与您的要求相反)。

这在 the documentations - 中有解释

Series.where(cond, other=nan, inplace=False, axis=None, level=None, try_cast=False, raise_on_error=True)

Return an object of same shape as self and whose corresponding entries are from self where cond is True and otherwise are from other.

所以你想做的是否定你现在正在做的事情。示例 -

In [22]: df.COL1.where((df.NEW>0 & (df[column_names].sum(axis=1) == 0)),df.NEW) 
Out[22]: 
0     2 
1   NaN 
2     0 
Name: COL1, dtype: float64 
 
In [23]: df.COL1.where(~(df.NEW>0 & (df[column_names].sum(axis=1) == 0)),df.NEW) 
Out[23]: 
0    1 
1    3 
2    7 
Name: COL1, dtype: float64 

另请注意 df.COL1 返回新系列,它不在原地,您可能需要将其分配回 df['COL1'] 。