首页 > 解决方案 > pandas 中值索引的输出,返回一个布尔数组

问题描述

在熊猫数据框中搜索唯一值索引时,它可以完美运行。但是当该值不唯一时,输出似乎是一个布尔数组:

将文件加载到:

import pandas as pd

df = pd.read_csv('test_file.csv')
print(df.head(10))

让我们说这是我正在处理的文件:

   test
0    10
1    20
2    10
3    20
4    20
5    20
6    10
7    10
8    10
9    30

现在,当我尝试获取列中不唯一的值的索引时:

output_index = df.set_index('test').index.get_loc(10)
print(output_index)

输出:

[ True False  True False False False  True  True  True False]

但是相同的代码在完成唯一值时工作得很好:

output_index = df.set_index('test').index.get_loc(30)
print(output_index)

输出:

9

那么获取在数据框中多次出现的值的索引的正确方法是什么?

标签: pythonpandas

解决方案


尝试这个:

output_index = df[df['test'] == 10].index 

如果您需要一份清单:

output_index = df[df['test'] == 10].index.to_list()

推荐阅读