Check if a value exists in pandas dataframe index

2019-03-08 13:03发布

问题:

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')

回答1:

This should do the trick

'g' in df.index


回答2:

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.



回答3:

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


回答4:

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")