import pandas as pd
import numpy as np
binArray = np.array([[1, 0, 1]])
print(binArray)
list = ('Text0', 'Text1', 'Text2')
indx = pd.Index(list)
print(indx)
嗨!
如何在BinArray变量的帮助下提取'text0'和'text2'?请注意,BinArray&INDX在我的代码中始终为n。
谢谢!
一种可能性是使用np.where()
和np.take()
执行所需的操作。
binArray = np.array([[1, 0, 1]]) # Are you sure its not [] instead of [[]]
list = ('Text0', 'Text1', 'Text2')
indx = pd.Index(list)
# get indices for all 1 in binArray[0]
indices = np.where(binArray[0]==1)[0]
result = np.take(indx, indices)
您的结果现在是您需要的Index([u'Text0', u'Text2'], dtype='object')
。
解释
np.take()
将数组和索引作为参数,并返回与数组中索引相对应的值。例如:
>>> a = [4, 3, 5, 7, 6, 8]
>>> indices = [0, 1, 4]
>>> np.take(a, indices)
array([4, 3, 6])
np.where()
根据给定条件从给定数组中返回元素。在这种情况下,我们请求来自binArray[0]
的所有索引,其中该值为1
,其相应的 indx
中的映射是您最终结果。