python删除第一行_python-有效删除数组的每一行(如果它以纯nu...

这是一个利用以下事实的事实:它们是使用矩阵乘法进行降维的正数-

def setdiff_nd_positivenums(a,b):

s = np.maximum(a.max(0)+1,b.max(0)+1)

return a[~np.isin(a.dot(s),b.dot(s))]

样品运行-

In [82]: a

Out[82]:

array([[0, 1],

[2, 3],

[1, 2],

[4, 2]])

In [83]: b

Out[83]:

array([[2, 3],

[4, 2]])

In [85]: setdiff_nd_positivenums(a,b)

Out[85]:

array([[0, 1],

[1, 2]])

同样,第二个数组b似乎是a的子集.因此,我们可以利用np.searchsorted进一步利用该方案来提高性能,就像这样-

def setdiff_nd_positivenums_searchsorted(a,b):

s = np.maximum(a.max(0)+1,b.max(0)+1)

a1D,b1D = a.dot(s),b.dot(s)

b1Ds = np.sort(b1D)

return a[b1Ds[np.searchsorted(b1Ds,a1D)] != a1D]

时间-

In [146]: np.random.seed(0)

...: a = np.random.randint(0,9,(1000000,2))

...: b = a[np.random.choice(len(a), 10000, replace=0)]

In [147]: %timeit setdiff_nd_positivenums(a,b)

...: %timeit setdiff_nd_positivenums_searchsorted(a,b)

10 loops, best of 3: 101 ms per loop

10 loops, best of 3: 70.9 ms per loop

对于通用数字,这是另一个使用视图的视图-

# https://stackoverflow.com/a/45313353/ @Divakar

def view1D(a, b): # a, b are arrays

a = np.ascontiguousarray(a)

b = np.ascontiguousarray(b)

void_dt = np.dtype((np.void, a.dtype.itemsize * a.shape[1]))

return a.view(void_dt).ravel(), b.view(void_dt).ravel()

def setdiff_nd(a,b):

# a,b are the nD input arrays

A,B = view1D(a,b)

return a[~np.isin(A,B)]

样品运行-

In [94]: a

Out[94]:

array([[ 0, 1],

[-2, -3],

[ 1, 2],

[-4, -2]])

In [95]: b

Out[95]:

array([[-2, -3],

[ 4, 2]])

In [96]: setdiff_nd(a,b)

Out[96]:

array([[ 0, 1],

[ 1, 2],

[-4, -2]])

时间-

In [158]: np.random.seed(0)

...: a = np.random.randint(0,9,(1000000,2))

...: b = a[np.random.choice(len(a), 10000, replace=0)]

In [159]: %timeit setdiff_nd(a,b)

1 loop, best of 3: 352 ms per loop

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值