TylerNG
TylerNG

Reputation: 941

Pandas extract data by indexes

I have this df where I have 2 indexes and I want to extract them by group.

df where Group and Name here are indexes

         Name  1  2  3 
Group1   xyz   1  1  1 
         abc   2  2  2
Group2   ijk   3  3  3
         lmn   4  4  4

I want to get df1:

         Name  1  2  3 
Group1   xyz   1  1  1 
         abc   2  2  2

and df2:

         Name  1  2  3 
Group2   ijk   3  3  3
         lmn   4  4  4

I also want convert Name into a column instead of being an index.

I did this by export df into excel then read them about but I figure there must a more efficient way to do this.

Thanks!

Upvotes: 1

Views: 37

Answers (1)

BENY
BENY

Reputation: 323226

Using groupby+reset_index

l=[d for _,d in df.reset_index(level='Name').groupby(level=0)]
l
Out[1238]: 
[       Name  1  2  3
 Group1  xyz  1  1  1
 Group1  abc  2  2  2,        Name  1  2  3
 Group2  ijk  3  3  3
 Group2  lmn  4  4  4]



df1,df2=l[0],l[1]

df1
Out[1240]: 
       Name  1  2  3
Group1  xyz  1  1  1
Group1  abc  2  2  2
df2
Out[1241]: 
       Name  1  2  3
Group2  ijk  3  3  3
Group2  lmn  4  4  4

Upvotes: 1

Related Questions