Enigmatic
Enigmatic

Reputation: 4138

Replacing Pandas index with row values

Task:

I would like to replace index values (i.e 0,1,2,3,4 etc.) with the values under Main, while removing Main as it no longer has use.

df:

                  Main             Ing 
0                  A              Apple            
1                  B              Bread            
2                  Z              Cheese            
3                  E              Egg            
4                  D              Dough           
5                  X              Pasta   

My Goal:

Output:

                Ing 
A              Apple            
B              Bread            
Z              Cheese            
E              Egg            
D              Dough           
X              Pasta   

I'm sure it's a pretty simple solution but I have no idea. Thanks in advance.

Upvotes: 2

Views: 57

Answers (1)

jezrael
jezrael

Reputation: 862431

Use set_index:

df = df.set_index('Main')
print (df)
         Ing
Main        
A      Apple
B      Bread
Z     Cheese
E        Egg
D      Dough
X      Pasta

If need remove index name Main add rename_axis:

df = df.set_index('Main').rename_axis(None)
print (df)
      Ing
A   Apple
B   Bread
Z  Cheese
E     Egg
D   Dough
X   Pasta

Or set it to None:

df = df.set_index('Main')
df.index.name = None
print (df)
      Ing
A   Apple
B   Bread
Z  Cheese
E     Egg
D   Dough
X   Pasta

Upvotes: 6

Related Questions