创建的新列具有不正确的值

new column created has incorrect values

我有两个列a和b,都是二元变量。

    a b
    1 1
    0 1
    1 1
    0 0
    0 0
...
    1 1
    0 1
    1 0
    0 0
    0 0

我需要在检查以下条件后创建一个新变量 c:

def test_func(data):
    if data['a'] == 0 & data['b'] == 0:
        return 1;
    if data['a'] == 0 & data['b'] == 1:
        return 2;
    if data['a'] == 1 & data['b'] == 0:
        return 3;
    if data['a'] == 1 & data['b'] == 1:
        return 4;
    else:
        return 0

data['c'] = data.apply(test_func, axis=1)
print(data['c'] )

但我只在新的 c 列中得到值 1 和 4,我也得到了值 0。实际上,有所有四种组合(没有组合可以得到 0)。但没有将它们放在新的 c 列中。我可以知道如何正确执行此操作吗?

Desired output:
    a b c
    1 1 4
    0 1 2
    1 1 4
    0 0 1
    0 0 1
...
    1 1 4
    0 1 2
    1 0 3 
    0 0 1
    0 0 1


But what i got:
        a b c
        1 1 4
        0 1 1
        1 1 4
        0 0 1
        0 0 1
    ...
        1 1 4
        0 1 1
        1 0 0 
        0 0 1
        0 0 1

我认为您尝试做的事情的问题来自于在您的代码中使用 &,而我认为您想要的是 and。这两个在 python 中不相同(更多 info/examples here)但基本上 and 检查两个语句是否计算为 True& 是按位运算符。

所以,尝试将您的代码更改为:

def test_func(data):
    if data['a'] == 0 and data['b'] == 0:
        return 1;
    if data['a'] == 0 and data['b'] == 1:
        return 2;
    if data['a'] == 1 and data['b'] == 0:
        return 3;
    if data['a'] == 1 and data['b'] == 1:
        return 4;
    else:
        return 0

附带说明一下,您应该尽量避免在一个函数中使用如此多的 return 语句,因为它会变得非常混乱。例如,您可以将其替换为您在每个 if 块中更改的 result 变量,并且还可以更改您的个人 if 语句以也使用 elif.

我对这个基本示例的建议是:

def test_func(data):
    result = 0

    if data['a'] == 0 and data['b'] == 0:
        result = 1
    elif data['a'] == 0 and data['b'] == 1:
        result = 2
    elif data['a'] == 1 and data['b'] == 0:
        result = 3
    elif data['a'] == 1 and data['b'] == 1:
        result = 4
    
    return result

数据是字典吗?从你的符号看来是这样的。 定义的 apply(func, val) 方法是什么? 假设你有一个像 {"a":1, "b":1} 这样的字典数据或 1 和 0 的任意组合 a 和 b,使用你的函数将是:

data={"a":1, "b":0} #for example
def test_func(*args):
    if data['a'] == 0 and data['b'] == 0:
        return 1
    elif data['a'] == 0 and data['b'] == 1:
        return 2
    elif data['a'] == 1 and data['b'] == 0:
        return 3
    elif data['a'] == 1 and data['b'] == 1:
        return 4
    else:
        return 0

data["c"]=test_func(data)
print(data["c"])

如果你使用括号,你仍然可以使用 &

def test_func(x):
    if ((x.a==0)&(x.b==0)):
        return 1;
    if ((x.a==0)&(x.b==1)):
        return 2;
    if ((x.a==1)&(x.b==0)):
        return 3;
    if ((x.a==1)&(x.b==1)):
        return 4;
    else:
        return 0