Murtaza Haji
Murtaza Haji

Reputation: 1193

How to search in a column that has been converted to index in dataframe?

This is my dataframe

d = {'id':['a','a','a','b','b','b','c','c','c','d','d','d'],
 'seg':[1,2,3,1,2,3,1,2,3,1,2,3],
 'type':['y','y','y','z','z','z','y','y','z','z','z','y']
}
df= pd.DataFrame(d)

df1 = df.set_index(['id','type'])

Why am I not able to use df1.loc[df1['id'] == 'a'] to filter for ain id column?

What is the way to do it for columns which are set as index?

Upvotes: 1

Views: 24

Answers (2)

BENY
BENY

Reputation: 323356

I will try query notice this will carry the index id as well :-)

df1.query("id=='a'")
         seg
id type     
a  y       1
   y       2
   y       3

Upvotes: 1

Quang Hoang
Quang Hoang

Reputation: 150785

Because id is part of df1's index now, not a column. You can use [] access on column only. But since id is first level index, you can do:

df1.loc['a']

which gives:

      seg
type     
y       1
y       2
y       3

Upvotes: 1

Related Questions