You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何利用二进制NumPy数组提取Pandas Index中的指定元素?

解决方案:用布尔索引提取对应元素

嘿,这个需求很好实现,咱们直接利用numpy的数组转换和pandas的布尔索引就能搞定!

首先先修正个小细节:你的代码里把变量名设成了list,这会覆盖Python的内置函数list(),建议改成list_items这类不会冲突的名字哦。

完整实现代码

import pandas as pd
import numpy as np

binArray = np.array([[1, 0, 1]])
list_items = ('Text0', 'Text1', 'Text2')
indx = pd.Index(list_items)

# 核心筛选逻辑
selected_texts = indx[binArray.flatten().astype(bool)]
print(selected_texts)

代码解释

  • binArray.flatten():把你的二维数组[[1,0,1]]转换成一维数组[1,0,1],这样才能和indx的长度匹配
  • .astype(bool):把数组里的1转为True,0转为False,得到布尔数组[True, False, True]
  • indx[布尔数组]:pandas的Index支持布尔索引,会自动保留对应位置为True的元素,也就是你要的'Text0'和'Text2'

另一种等价写法

因为你的binArray只有一行,也可以直接取第一维来扁平化,效果完全一样:

selected_texts = indx[binArray[0].astype(bool)]

这个方法不管N是多少都适用,只要binArray和indx长度一致,且binArray里只有0和1就行~

内容的提问来源于stack exchange,提问作者user1455613

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:37:47