np.where与np.logical一起崩溃python



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

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

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

错误消息如下:

Python已停止工作

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

对原因以及如何解决有什么想法吗?谢谢

您为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.

这个答案完全解决了上述场景,提供了链接条件、np.reducefunctools.reduce或用显式轴替换所有条件的选项。

作为这样的

DebitCond1a=np.logical_and(df['P1_DR']<0, df['P1_DR']<df['P1_CR'])

DebitCond1=np.logical_and(DebitCond1a,df['P1_CR']<0)

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

最新更新