np.any返回一个对象数组中的对象,而不是布尔值?

2024-04-25 17:14:55 发布

您现在位置:Python中文网/ 问答频道 /正文

好吧,在试图回答this question时,我遇到了一件非常奇怪的事情。你知道吗

matrix = np.zeros(10000)
matrix[np.random.choice(10000, 100)] = np.random.rand(100)
matrix = matrix.reshape(10, 1000)

from scipy.sparse import lil_matrix
l = lil_matrix(matrix.T)
l.rows

Out: array([[], [], [], ..., [], [], []], dtype=object)

好的,我想知道哪些行有数据,所以我试着:

np.any(l.rows)

Out: [8]

。什么?

out = np.any(l.rows)
type(out)

Out: list

这是一张单子。里面有一个8。似乎。随机的。怎么回事?你知道吗

在处理之后,它似乎返回数组中第一个不是[]object。你知道吗

np.random.seed(9)
matrix = np.zeros(10000)
matrix[np.random.choice(10000, 100)] = np.random.rand(100)
matrix = matrix.reshape(10, 1000)

from scipy.sparse import lil_matrix
l = lil_matrix(matrix.T)
l.rows

Out: array([[], [], [5], ..., [], [], []], dtype=object)

np.any(l.rows)
Out: [5]

但是考虑到np.any只应该输出booleannp.array的布尔值,这是一个非常奇怪的结果。有人知道为什么会这样吗?你知道吗


Tags: fromobjectnpzerosanyrandomscipyout
1条回答
网友
1楼 · 发布于 2024-04-25 17:14:55

我找到了。显然,自2014年以来,它一直在Easy Fix名单上,但从上周起终于有了someone working on it。你知道吗

我应该知道我不是第一个尝试这种东西的傻瓜。你知道吗

在这种情况下,正确的用法是:

l[l.rows.astype(bool)]
Out: 
<97x10 sparse matrix of type '<class 'numpy.float64'>'
    with 100 stored elements in LInked List format>

相关问题 更多 >