Multiple slice in list indexing for numpy array

后端 未结 2 1352
北海茫月
北海茫月 2021-01-18 23:51

Numpy array admits a list of indices, for example

a = np.arange(1000)
l = list([1,44,66,33,90,345])
a[l] = 22

But this method don\'t work i

相关标签:
2条回答
  • 2021-01-19 00:12

    What comes to my mind:

    a = np.arange(1000)
    l = np.hstack(([1, 44, 66, 33, 90], np.arange(200, 300), np.arange(500, 600)))
    a[l] = 22
    

    I'm not sure if it's the simplest way, but it works.

    Edit: you're right that this is slower than using slices; but you cannot create a slice object with arbitrary values. Maybe you should just do several assignments then:

    %timeit a[np.hstack(([1, 44, 66, 33, 90], np.arange(200, 300), np.arange(500, 600)))] = 22
    10000 loops, best of 3: 39.5 us per loop
    
    %timeit a[[1, 44, 66, 33, 90]] = 22; a[200:300] = 22; a[500:600] = 22
    100000 loops, best of 3: 18.4 us per loop
    
    0 讨论(0)
  • 2021-01-19 00:26

    You can use fancy indexing to build an index list.

    l = numpy.array([1,44,66,33,90]+range(200,300)+range(500,600))
    a[l] = 22
    

    But as @Lev pointed out, this may not be any faster (though it almost certainly will be if you can precompute the index list).

    However, fancy indexing applies per-axis. So you can fancy index on one axis, and slice the others, if that helps at all:

    a = numpy.random.randn(4, 5, 6)
    l = numpy.array([1, 2])
    a[l, slice(None), slice(2, 4)] = 10
    
    0 讨论(0)
提交回复
热议问题