简体   繁体   中英

Deleting values from numpy array in Geometric progression

I want to delete element in incremental fashion eg

arr = [1,2,3,4,5,6,7,8,9,10]
# want to delete first element, second element, forth element
# 1,2,4,8,16,32,62.... till length of list
# For above example output will be
arr = [3,5,6,7,9,10]

arr is numpy array. Is there any way to define custom position to delete element. For now all I can think of as writing a custom function

import pandas as pd
import math
from numpy import random

arr = random.randint(100, size=(10))
get_index = [2**i for i in range(math.log(len(arr)))]
arr = numpy.delete(arr, index)

It will be great if there is some numpy function who can do that

you could create a set with the indices of the elements you do not want:

from math import log, ceil

arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

del_idx = {2 ** i for i in range(ceil(log(len(arr), 2)))}
print(del_idx)  # {8, 1, 2, 4}

res = [x for i, x in enumerate(arr, start=1) if i not in del_idx]
print(res)  # [3, 5, 6, 7, 9, 10]

the indices go up to log(len(arr), 2) .

you can then enumerate your array and ignore the indices you do not want.


with numpy you could do this:

import numpy as np
from math import log, ceil

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
del_idx = [2 ** i - 1 for i in range(ceil(log(len(arr), 2)))]
arr = np.delete(arr, del_idx)
import numpy as np
arr = #numpy array
# Filtering indices with no power of 2 numbers
idx = [i for (i,n) in enumerate(arr) if not n & (n - 1) == 0]
arr = arr[idx]

Or you can simply do this (one-line version):

arr = arr[(arr & (arr - 1) != 0)]

Where & is the bitwise operator . Filter extracted from here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM