在熊猫系列中选择多个索引值

时间:2019-02-26 16:13:08

标签: pandas

假设我有一个熊猫系列:

import pandas as pd
foo = pd.Series(data=[1,2,3], index=['a','b','c'])
foo

a    1
b    2
c    3
dtype: int64

将索引与值进行比较会返回一个不错的选择器数组:

foo.index == 'c'

array([False, False,  True], dtype=bool)

“ a”和“ c”([True,False,True])的选择器数组的表达式是什么?

不是这样的:

foo.index in ['a', 'c']

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

这是一个简单的示例,但真正的示例要复杂得多,我想选择10或15个项目,所以我想使用一种简洁的格式,最好列出要按名称选择的元素。

我正在使用熊猫0.23.4。

1 个答案:

答案 0 :(得分:2)

您可以使用:

foo.index.isin(['a','b'])

返回ab的选择器数组,如果需要不同的值,则可以任意更改列表。

相关问题