【问题标题】:Nested condition in pandas caused ValueError: The truth value of a Series is ambiguouspandas 中的嵌套条件导致 ValueError:Series 的真值不明确
【发布时间】:2021-10-15 23:29:31
【问题描述】:

熊猫数据框是:

df = pd.DataFrame([['A', 1, 20], ['A', 2, 30], ['B', 1, 50], ['B', 3, 45], ['A', 4, 60], ['B', 5, 70]])
df.columns = ['Type', 'P', 'X']

df:

  Type  P   X
0    A  1  20

1    A  2  30

2    B  1  50

3    B  3  45

4    A  4  60

5    B  5  70

期望:

我想应用嵌套条件来计算一个值并将其附加为一个新列。

这就是我所做的:

result = 0
if (df.Type == 'A'):
    if df.P % 2 == 0:
        result = df.X+10
    else:
        restult = df.X+20
else:
    if df.P % 2 == 0:
        result = df.X+30
    else:
        result = df.X+40
df['Result'] = result

预期的输出是:

 Type  P   X   Result

0    A  1  20   40

1    A  2  30   40

2    B  1  50   90

3    B  3  45   85

4    A  4  60   70

5    B  5  70   110

但它失败并出现错误:ValueError:一个系列的真值是不明确的。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。

我已经挖掘了其他线程,但它们似乎是其他问题。

欢迎提出任何建议

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    使用np.select(listof conditions, listofchoices, alternative)

    condition=[(df.Type == 'A')&(df.P % 2 != 0),(df.Type == 'A')&(df.P % 2 == 0), (df.Type == 'B')&(df.P % 2 == 0)]
        
    choices= [df.X+20,df.X+10,df.X+30]
    
    df['result'] = np.select(condition, choices,df.X+40)
    
        Type  P   X  result
    0    A  1  20      40
    1    A  2  30      40
    2    B  1  50      90
    3    B  3  45      85
    4    A  4  60      70
    5    B  5  70     110
    

    【讨论】:

    • 谢谢!但是这样一来,如果df.Type == 'B',那么这个return就是False,那么无论df.P是奇数还是偶数,整个return总是False。到目前为止,考虑 df.P 是奇数还是偶数的“与”条件没有任何意义。我对吗?如果我想使用条件语句,我应该更正什么?
    • 您对 B 的期望结果是什么,我没有看到 B 在您的情况下,所以不知道如何考虑。能简单解释一下吗?
    • 很抱歉造成混乱,我已经更改了一些细节以澄清一些混乱,并添加了预期的输出。请你再检查一遍好吗?谢谢!
    【解决方案2】:

    if 运算符未矢量化,不能与 Series 一起使用,请改用 np.select

    type_a, p_even = df.Type == 'A', df.P % 2 == 0
    amount = np.select(
        [type_a & p_even, type_a & ~p_even, ~type_a & p_even, ~type_a & ~p_even], 
        [10, 20, 30, 40]
    )
    df['Result'] = df.X + amount
    
    df
      Type  P   X  Result
    0    A  1  20      40
    1    A  2  30      40
    2    B  1  50      90
    3    B  3  45      85
    4    A  4  60      70
    5    B  5  70     110
    

    【讨论】:

      猜你喜欢
      • 2018-07-05
      • 2021-09-10
      • 2020-08-03
      • 1970-01-01
      • 1970-01-01
      • 2020-03-25
      • 2019-10-29
      • 2021-08-14
      • 2021-06-02
      相关资源
      最近更新 更多