hedebyhedge
hedebyhedge

Reputation: 455

Pandas: groupby column and set it as index

If I have a dataframe such as this:

df1 = pd.DataFrame({'A':[1,2,3,4,5,6,7,8],
               'B':['a','b','c','d','e','f','g','h'],
               'C':['u1','u2','u4','u3','u1','u1','u2','u4']})  

And would like it to be as such, with u1 to u4 as the indices.

    A  B   
u1  1  a  
    5  e  
    6  f  
u2  2  b  
    7  g  
u3  4  d  
u4  3  c  
    8  h  

What's the best way to groupby a column and then set it as the index? I've tried to directly .set_index('C'), but it sets an index for every instance of u1 to u4.

Upvotes: 0

Views: 1261

Answers (1)

Charles R
Charles R

Reputation: 1661

You can set C as an index and then sort it :

df1.set_index('C').sort_index(axis=0)

Upvotes: 2

Related Questions