Reputation: 1326
Please help me read and use the great Pandas documentation better.
E.g.pandas.Index.contains and the overview of attributes and methods for the Pandas Index class.
In this case, I want to check if a key is in the index before applying
dataframe.loc['key',['column']]) # first check if key is in index to avoid KeyError: 'the label [key] is not in the [index]'
I want to use the method contains(key) ("return a boolean if this key is IN the index").
So I incorrectly tried dataframe.Index.contains. But it should be index and not Index. So why is it written with a capital in the documentation?
Also, it should be with .str in between index and contains:
dataframe.index.str.contains('key')) # not dataframe.Index.contains
It is my fault, but how should I know this from the documentation?
Upvotes: 0
Views: 66
Reputation: 30605
If you want to know whether a key is in index then use .isin
i.e ("return a boolean array if this key is IN the index")
df= pd.DataFrame([['a','b'],['b','c'],['c','z'],['d','b']])
0 1
0 a b
1 b c
2 c z
3 d b
df.index.isin([1,2])
Output:
array([False, True, True, False], dtype=bool)
For a scalar use in
i.e. k in df.index
where k is any number or scalar
Eg:
2 in df.index
True
df.index.isin([2])
array([False, False, True, False], dtype=bool)
Upvotes: 1