Check if a value exists in pandas dataframe index

2019-03-08 12:40发布

I am sure there is an obvious way to do this but cant think of anything slick right now.

Basically instead of raising exception I would like to get True or False to see if a value exists in pandas df index.

df = pandas.DataFrame({'test':[1,2,3,4]}, index=['a','b','c','d'])

df.loc['g']  # (should give False)

What I have working now is the following

sum(df.index == 'g')

4条回答
霸刀☆藐视天下
2楼-- · 2019-03-08 12:46

Multi index works a little different from single index. Here are some methods for multi-indexed dataframe.

df = pd.DataFrame({'col1': ['a', 'b','c', 'd'], 'col2': ['X','X','Y', 'Y'], 'col3': [1, 2, 3, 4]}, columns=['col1', 'col2', 'col3'])
df = df.set_index(['col1', 'col2'])

in df.index works for the first level only when checking single index value.

'a' in df.index     # True
'X' in df.index     # False

Check df.index.levels for other levels.

'a' in df.index.levels[0] # True
'X' in df.index.levels[1] # True

Check in df.index for an index combination tuple.

('a', 'X') in df.index  # True
('a', 'Y') in df.index  # False
查看更多
闹够了就滚
3楼-- · 2019-03-08 12:56

Just for reference as it was something I was looking for, you can test for presence within the values or the index by appending the ".values" method, e.g.

g in df.<your selected field>.values
g in df.index.values

I find that adding the ".values" to get a simple list or ndarray out makes exist or "in" checks run more smoothly with the other python tools. Just thought I'd toss that out there for people.

查看更多
别忘想泡老子
4楼-- · 2019-03-08 12:56
df = pandas.DataFrame({'g':[1]}, index=['isStop'])

#df.loc['g']

if 'g' in df.index:
    print("find g")

if 'isStop' in df.index:
    print("find a") 
查看更多
姐就是有狂的资本
5楼-- · 2019-03-08 12:58

This should do the trick

'g' in df.index
查看更多
登录 后发表回答