【问题标题】:Python Value Error when creating new column using np.where使用 np.where 创建新列时出现 Python 值错误
【发布时间】:2021-06-23 06:16:26
【问题描述】:

问题

我正在尝试使用 if 语句 (np.where) 比较两列中的值,但是我不断收到错误消息。我无法弄清楚为什么,我以前在数据框中使用 np.where 没有问题。

ValueError:Series 的真值不明确。使用a.empty, a.bool()、a.item()、a.any() 或 a.all()。

示例

df = pd.DataFrame(
    {'colors': ['red', 'white', 'blue'], 
     'n1': [1, 2, 3], 
     'n2': [4, 6, 7], 
     'n3': [5, 3, 2]
     }
)

df['test'] = np.where(
    df.n1 > df.n2, 
    max(0, df.n1 - df.n3), 
    df.n3
)

错误信息

Traceback (most recent call last):
  File "C:/Users/user/PycharmProjects/project/example.py", line 15, in <module>
    df['test'] = np.where(df.n1 > df.n2, max(0, df.n1 - df.n3), df.n3)
  File "C:\Users\user\Continuum\anaconda3\envs\CondaEnv\lib\site-packages\pandas\core\generic.py", line 1442, in __nonzero__
    f"The truth value of a {type(self).__name__} is ambiguous. "
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Process finished with exit code 1

非常感谢任何帮助。

【问题讨论】:

    标签: python pandas numpy


    【解决方案1】:

    使用numpy.maximum:

    df['test'] = np.where(
    df.n1 > df.n2, 
    np.maximum(0, df.n1 - df.n3), 
    df.n3)
    print (df)
      colors  n1  n2  n3  test
    0    red   1   4   5     5
    1  white   2   6   3     3
    2   blue   3   7   2     2
    

    【讨论】:

    • 太棒了!这解决了这个问题。非常感谢您的快速回复。你太快了,我还不能接受答案,但会在 10 分钟内完成。
    猜你喜欢
    • 2019-01-14
    • 1970-01-01
    • 2018-02-01
    • 1970-01-01
    • 2020-09-22
    • 2019-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多