【问题标题】:Np.Where with multiple or nested conditions producing errorNp.Where 有多个或嵌套条件产生错误
【发布时间】:2020-07-16 22:22:13
【问题描述】:

我有一个如下所示的数据框:

    col1    col2
0   abc      0
1   def     -1
2   ghi      1
3   jkl    -0.5

再现:

data = {'col1':  ['abc', 'def','ghi','jkl'],
        'col2': ['0', '-1','1','-0.5']
        }

df = pd.DataFrame (data, columns = ['col1','col2'])

我想添加第三列,其内容基于 col2 的条件评估 所以结果如下:

    col1    col2    col3
0   abc      0      blue
1   def     -1      red
2   ghi      1      green
3   jkl    -0.5     red

我当前的代码是这样的:

df['col3'] = np.where((df['col2'] >=1,'green',
                       (df['col2'] ==0, 'blue',
                         (df['col2'] <0, 'red'))))

但是,这目前失败并出现以下错误:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-151-a19019bc0d01> in <module>
      1 df['col3'] = np.where((df['col2'] >=1,'green',
      2                        (df['col2'] ==0, 'blue',
----> 3                          (df['col2'] <0, 'red'))))

//anaconda3/lib/python3.7/site-packages/pandas/core/generic.py in __nonzero__(self)
   1476         raise ValueError("The truth value of a {0} is ambiguous. "
   1477                          "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
-> 1478                          .format(self.__class__.__name__))
   1479 
   1480     __bool__ = __nonzero__

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

能否请您解释错误并建议我如何实现最终目标?

谢谢

【问题讨论】:

标签: python-3.x numpy jupyter-notebook conditional-statements where-clause


【解决方案1】:
In [64]: data = {'col1':  ['abc', 'def','ghi','jkl'],
    ...:         'col2': ['0', '-1','1','-0.5']
    ...:         }
    ...:
    ...: df = pd.DataFrame (data, columns = ['col1','col2'])

In [65]: df["col2"] = df["col2"].astype(float)

In [66]: def process(row):
    ...:     col2 = row["col2"]
    ...:     if col2 >=1: return "green"
    ...:     if col2 ==0: return "blue"
    ...:     if col2<0: return "red"
    ...:

In [67]: df["col3"] = df.apply(process,axis=1)

In [68]: df
Out[68]:
  col1  col2   col3
0  abc   0.0   blue
1  def  -1.0    red
2  ghi   1.0  green
3  jkl  -0.5    red

【讨论】:

  • 这就是我要找的。完美运行并且完全有意义。非常感谢
【解决方案2】:

你可以使用np.select:

import numpy as np
import pandas as pd

data = {'col1': ['abc', 'def','ghi','jkl'],
        'col2': ['0', '-1','1','-0.5']
        }

df = pd.DataFrame (data, columns = ['col1','col2'])
df['col2'] = df['col2'].astype(float)

condlist = [df['col2'] >=1., df['col2'] ==0, df['col2'] <0]
choicelist = ['green', 'blue', 'red']
df['col3'] = np.select(condlist, choicelist)

给出:

>>> df
>>>     col1  col2   col3
>>>   0  abc   0.0   blue
>>>   1  def  -1.0    red
>>>   2  ghi   1.0  green
>>>   3  jkl  -0.5    red

【讨论】:

  • 非常感谢您的回答。我知道它是如何工作的,但我认为 function 和 apply() 方法可能对我的用例更有效。
猜你喜欢
  • 2020-04-02
  • 2022-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-22
  • 1970-01-01
  • 2017-02-02
  • 1970-01-01
相关资源
最近更新 更多