How to use str.contains on a DataFrame's index?

4,329 views
Skip to first unread message

Richard Stanton

unread,
May 8, 2013, 1:01:16 PM5/8/13
to pyd...@googlegroups.com
For a column of strings in a dataframe, I can use .str.contains() to check
which entries contain a given substring. For example,

ex['Date'].str.contains('Dec')

What's the best way to do this when the column I'm interested in is the
dataframe's index? The method above doesn't work:

In [2]: ex.index.str.contains('Dec')

AttributeError: 'Index' object has no attribute 'str'


I can write a little function and use map() (which is what I actually
did), but it would be nicer if there were some easy way to use all of
pandas' vectorized functions on the index as well as on internal columns
of the dataframe. Is this possible (short of bringing the index back into
the dataframe and then shifting it out again afterwards)?

Thanks.

Richard Stanton

Jeff

unread,
May 8, 2013, 1:06:15 PM5/8/13
to pyd...@googlegroups.com
in >= 0.11:

df.index.to_series().str.contains('foo')


these methods only exist on series objects
the reason is that indices can be other things, like multi-indcies where
these methods don't make sense, so just wrap as a Series or use to_series
Reply all
Reply to author
Forward
0 new messages