Skip to main content
 首页 » 编程设计

python之根据给出 ValueError 的函数创建一个新列

2024年11月24日9cmt

我有一个包含两列的数据框:一列包含一个零值和一个值,另一列包含一个数值。

  ZeroOne   Value 
    0       10 
    1       20 
    0       15 

目标是创建一个新列,如果 ZeroOne 列包含“0”,则放置值列的值。如果 ZeroOne 值为 1,则新列应为 0。因此,在我的示例中,结果应为:

  ZeroOne   Value   Result 
   0        10          10 
   1        20           0 
   0        15          15 

我试过做一个函数:

def function(a,b): 
    if a == 1: 
        return b 
    else: 
        return 0 

然后做了变量a和b

    a = df['ZeroOne'] 
    b = df['Value'] 

在此之后,我添加了一个具有此功能的新列

   df['result'] = function(a,b) 

它一直给我值错误:

   The truth value of a Series is ambiguous. Use a.empty, a.bool(),  
   a.item(), a.any() or a.all(). 

我怎样才能达到我的结果,我做错了什么?

请您参考如下方法:

尝试使用 where:

import pandas as pd 
 
df = pd.DataFrame.from_dict({"ZeroOne": [0, 1, 0], "Value": [10, 20, 15]}) 
 
df['Result'] = (df['Value'].where(cond=df['ZeroOne'] == 0, other=0)) 
 
print(df) 

输出:

   Value  ZeroOne  Result 
0     10        0      10 
1     20        1       0 
2     15        0      15