[英]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. arr 是numpy
数组。 Is there any way to define custom position to delete element.有什么方法可以定义自定义 position 来删除元素。 For now all I can think of as writing a custom function现在我能想到的就是写一个自定义的 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如果有一些 numpy function 可以做到这一点,那就太好了
you could create a set
with the indices of the elements you do not want:您可以使用不需要的元素的索引创建一个set
:
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)
.索引 go 到log(len(arr), 2)
。
you can then enumerate
your array and ignore the indices you do not want.然后你可以enumerate
你的数组并忽略你不想要的索引。
with numpy
you could do this:使用numpy
你可以这样做:
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 .从这里提取的过滤器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.