基于一个函数生成一个新的列

2024-10-01 00:36:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含两列的数据帧:一列包含一个0和一个值,另一列包含一个数值

  ZeroOne   Value
    0       10
    1       20
    0       15

目标是生成一个新列,如果ZeroOne列包含“0”,则将value列的值放入其中。如果zerone值是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().

我怎样才能达到我的目标?我做错了什么


Tags: 数据函数示例目标dfreturnifvalue
2条回答

对于这种情况,您可以使用numpy库中的np.where

df['Result'] = np.where(df['ZeroOne'] == 0, df['Value'], 0)

它类似于亚当斯解,但你也可以给它添加其他条件,函数中的第一个空格给出了条件,如果它是真的会发生什么,如果它是错的会发生什么

尝试使用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

相关问题 更多 >