【问题标题】:new column created has incorrect values创建的新列的值不正确
【发布时间】:2021-03-04 14:10:26
【问题描述】:

我有两个列 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

【问题讨论】:

  • 您能否添加一个可重现的示例?这只是您数据的简化或模拟版本。
  • 是的!我编辑了我的问题

标签: python loops variables apply


【解决方案1】:

我相信您尝试做的事情的问题来自在您的代码中使用&,而我相信您想要的是and。这两个在 python 中不一样(更多信息/示例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

【讨论】:

  • 是的.. 这就是问题所在:D
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

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

    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"])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-30
      • 2015-07-15
      • 1970-01-01
      相关资源
      最近更新 更多