Python 从numpy数组中删除元素时跟踪删除的索引
我想从numpy数组中删除不满足特定条件的债券的元素。我知道我可以用下面的代码行来做这件事。不过,我还想跟踪已删除元素的索引,我想知道如何才能做到这一点Python 从numpy数组中删除元素时跟踪删除的索引,python,arrays,numpy,Python,Arrays,Numpy,我想从numpy数组中删除不满足特定条件的债券的元素。我知道我可以用下面的代码行来做这件事。不过,我还想跟踪已删除元素的索引,我想知道如何才能做到这一点 theoretical_price_for_bonds = theoretical_price_for_bonds[(theoretical_price_for_bonds>75)] 我尝试使用循环从numpy数组中动态删除元素。价格还行,但是下降的指数结果只是一个充满无的列表: #To insert values into a lis
theoretical_price_for_bonds = theoretical_price_for_bonds[(theoretical_price_for_bonds>75)]
我尝试使用循环从numpy数组中动态删除元素。价格还行,但是下降的指数
结果只是一个充满无
的列表:
#To insert values into a list dynamically
class GrowingList(list):
def __setitem__(self, index, value):
if index >= len(self):
self.extend([None]*(index + 1 - len(self)))
list.__setitem__(self, index, value)
count = 0
dropped_indices = GrowingList()
for x,value in np.ndenumerate(theoretical_price_for_bonds):
count = count + 1
if count < theoretical_price_for_bonds.shape[0]:
if theoretical_price_for_bonds[count] < 75:
theoretical_price_for_bonds = np.delete(theoretical_price_for_bonds, (count), axis=0)
dropped_indices[count] = count
#将值动态插入列表
类增长列表(列表):
定义设置项(自身、索引、值):
如果索引>=len(自):
self.extend([None]*(索引+1-len(self)))
列表。设置项(自身、索引、值)
计数=0
删除的索引=增长列表()
对于x,以np.ndenumerate(债券的理论价格)表示的值:
计数=计数+1
如果债券的计数<理论价格.形状[0]:
如果债券的理论价格[计数]<75:
债券的理论价格=np。删除(债券的理论价格,(计数),轴=0)
删除的索引[计数]=计数
谢谢如果要跟踪已删除元素的索引,请按住用于索引到数组中的布尔掩码,然后使用
np。其中
:
>>> x = np.array([2,8,3,4,7,6,1])
>>> lix = x > 4
>>> x = x[lix] # this "drops" everything 4 or less
>>> x
array([8, 7, 6])
>>> [dropped] = np.where(~lix) # find the indices that weren't dropped
>>> dropped
array([0, 2, 3, 6])
您还可以考虑使用一个具有<代码>的索引< >代码>属性,该属性可以用来跟踪丢失的值:
import numpy as np
import pandas as pd
s = pd.Series(np.array([2,8,3,4,7,6,1]))
print(s.values, s.index)
# (array([2, 8, 3, 4, 7, 6, 1]), Int64Index([0, 1, 2, 3, 4, 5, 6], dtype='int64'))
s2 = s[s > 4]
print(s2.values, s2.index)
# (array([8, 7, 6]), Int64Index([1, 4, 5], dtype='int64'))