【问题标题】:np.where with np.logical_and crashes pythonnp.where 与 np.logical_and 崩溃 python
【发布时间】:2022-01-18 01:59:28
【问题描述】:

我正在使用 numpy 构建复杂的 excel IF 公式,第一个条件如下:

DebitCond1 = np.where(np.logical_and(df['Debit']<0, df['Credit']<0, df['Debit']<df['Credit']))

每次我运行它时 Python 都会崩溃(在多台机器上尝试过)。有两个条件是可以的,但是这三个条件的组合似乎有问题。

报错信息如下:

Python 已停止工作

一个问题导致程序停止正常工作。 如果有可用的解决方案,Windows 将关闭该程序并通知您。

关于原因以及如何解决的任何想法?谢谢!

【问题讨论】:

    标签: python numpy


    【解决方案1】:

    您正在向np.logical_and() 提供三个值。第三个被解释为out= 参数,您可能并不打算这样做。

    这是np.logical_and()的签名

    numpy.logical_and(x1, x2, /, out=None, *, where=True,
                      casting='same_kind', order='K', dtype=None,
                      subok=True[, signature, extobj])
    

    以及文档摘录:

    Compute the truth value of x1 AND x2 element-wise.
    
    Parameters
    ----------
    x1, x2 : array_like
        Input arrays.
        If ``x1.shape != x2.shape``, they must be broadcastable to a common
        shape (which becomes the shape of the output).
    out : ndarray, None, or tuple of ndarray and None, optional
        A location into which the result is stored. If provided, it must have
        a shape that the inputs broadcast to. If not provided or None,
        a freshly-allocated array is returned. A tuple (possible only as a
        keyword argument) must have length equal to the number of outputs.
    

    【讨论】:

      【解决方案2】:

      This answer 完全解决了上述情况,并提供了链接条件、np.reduce 它们、functools.reduce 它们或用显式轴替换所有条件的选项。

      这样

      DebitCond1a=np.logical_and(df['P1_DR']&lt;0, df['P1_DR']&lt;df['P1_CR'])

      DebitCond1=np.logical_and(DebitCond1a,df['P1_CR']&lt;0)

      是在这种情况下合并两个以上条件的一种方法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-11-14
        • 2020-09-06
        • 2015-09-13
        • 2013-03-12
        • 2014-01-02
        • 2017-06-30
        • 1970-01-01
        相关资源
        最近更新 更多