Python 检查多索引数据帧中的一个特定索引中是否存在值

Python 检查多索引数据帧中的一个特定索引中是否存在值,python,pandas,dataframe,indexing,Python,Pandas,Dataframe,Indexing,我有一个名为df的multi-index数据框架,其中包含3个索引(水果、颜色、味道)。我想搜索一个特定的索引,即索引为颜色,并查看其中是否存在值 例如:代码看起来像这样Color是数据帧中的索引,而不仅仅是列 if 'purple' in 'Color': print('yes') else: print('no') 我只希望它搜索颜色而不是任何其他索引/列 Quantity Quality Fruit Color

我有一个名为
df
multi-index
数据框架,其中包含3个
索引(水果、颜色、味道)。我想搜索一个特定的
索引
,即
索引
颜色
,并查看其中是否存在

例如:代码看起来像这样
Color
是数据帧中的
索引,而不仅仅是列

if 'purple' in 'Color':
    print('yes')
else:
    print('no')
我只希望它搜索
颜色
而不是任何其他
索引/列

                       Quantity     Quality
Fruit   Color   Taste
apple   red     tart     12          good
lemon   yellow  sour     11          average
grapes  purple  sweet     5          bad
lime    green   citrus    3          excellent
非常感谢您抽出时间

尝试从数据帧中获取横截面:

df.xs('purple', level=1, drop_level=False)
只是为了测试它是否存在,检查横截面是否存在:


或者,使用和查看是否存在任何匹配项:

df.reset_index('Color')['Color'].eq('purple').any()
尝试从数据帧中获取横截面:

df.xs('purple', level=1, drop_level=False)
只是为了测试它是否存在,检查横截面是否存在:


或者,使用和查看是否存在任何匹配项:

df.reset_index('Color')['Color'].eq('purple').any()

如果需要表格输出,可以使用此选项:

def check(data:pd.DataFrame,l:list):
    c = data.index.get_level_values("Color").isin(l)
    return np.where(c,'yes','no')

df['Result'] = check(df,['purple'])


如果需要表格输出,可以使用此选项:

def check(data:pd.DataFrame,l:list):
    c = data.index.get_level_values("Color").isin(l)
    return np.where(c,'yes','no')

df['Result'] = check(df,['purple'])


您可以使用
get\u level\u value
进行筛选

if "purple" in df.index.get_level_values('Color'):
    print('yes')
else:
    print('no')

您可以使用
get\u level\u value
进行筛选

if "purple" in df.index.get_level_values('Color'):
    print('yes')
else:
    print('no')

看着你的个人资料,我注意到你从未接受过答案。请返回并回顾您之前的问题,并单击您选择的答案左侧的复选标记。(有关信息,请参阅)查看您的个人资料,我注意到您从未接受过答复。请返回并回顾您之前的问题,并单击您选择的答案左侧的复选标记。(有关信息,请参阅)
print(df)

                       Quantity    Quality Result
Fruit  Color  Type                              
apple  red    tart          12       good     no
lemon  yellow sour          11    average     no
grapes purple sweet          5        bad    yes
lime   green  citrus         3  excellent     no
if "purple" in df.index.get_level_values('Color'):
    print('yes')
else:
    print('no')