kane
kane

Reputation: 6027

How to select dataframe row using regular expression on the index column?

I'm a pandas newbie. Here's the problem with an example

df = pd.DataFrame(data={'id':['john','joe','zack']})

I know that I can select rows where the "id" column contains "jo" like so

mask = df['id'].str.contains('jo')
df[mask]

But suppose that id column is indexed

df = df.set_index('id')

Now how do I select the rows where the index column contains "jo"?

Upvotes: 2

Views: 490

Answers (1)

jezrael
jezrael

Reputation: 863236

You need to change id to index:

df = pd.DataFrame(data={'id':['john','joe','zack'],
                        'col':[1,2,3]})

df = df.set_index('id')
df1 = df[df.index.str.contains('jo')]
print (df1)
      col
id       
john    1
joe     2

Upvotes: 7

Related Questions