如果我有一个numpy数组,例如:
A = np.array([[3, 2], [2, -1], [2, 3], [5, 6], [7,-1] , [8, 9]])
我想将数组的一部分与不具有-1的子数组分开。 请记住,我正在处理非常大的数据集,所以每次操作都可能很长,所以我尝试以最有效的方式记住内存和CPU时间。
我现在正在做的是:
slicing1 = np.where(A[:, 1] == -1)
with_ones = A[slicing1]
slicing2 = np.setdiff1d(np.arange(A.shape[0]), slicing1, assume_unique=True)
without_ones = A[slicing2]
有没有办法不创建slicing2
列表来减少内存消耗,因为它可能非常大?
有没有更好的方法来解决这个问题?
答案 0 :(得分:6)
一种方法是存储所需的逻辑索引,然后使用其逻辑否定存储在第二种情况下的索引:
In [46]: indx = A[:, 1] != -1
In [47]: A[indx]
Out[47]:
array([[3, 2],
[2, 3],
[5, 6],
[8, 9]])
In [48]: A[~indx]
Out[48]:
array([[ 2, -1],
[ 7, -1]])
答案 1 :(得分:1)
我设法使用:
创建without_onefilter(lambda x: x[1] != -1,A)
答案 2 :(得分:1)
或者您可以使用生成器功能:
A = np.array([[3, 2], [2, -1], [2, 3], [5, 6], [7,-1] , [8, 9]])
def filt(arr):
for item in arr:
if item[1]!=-1:
yield item
new_len = 0
for item in A:
if item[1] != -1:
new_len += 1
without_ones = np.empty([new_len, 2], dtype=int)
for i, item in enumerate(filt(A)):
without_ones[i] = item