Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete 2 column headers and shift the whole column row to left in dataframe

Delete 2 column headers and shift the whole column row to left in dataframe. Below is my dataframe.

    trash1  trash2  name    age
0   john    54      
1   mike    34      
2   suz 56      
3   tin 78      
4   yan 31  

i need the final df as below

    name    age
0   john    54      
1   mike    34      
2   suz 56      
3   tin 78      
4   yan 31      

I tried all the commands but its deleting the whole column. Please help me in this.

like image 231
pankaj sonawane Avatar asked Dec 06 '25 07:12

pankaj sonawane


2 Answers

Code

out = df.shift(2, axis=1).drop(['trash1', 'trash2'], axis=1)

out

    name    age
0   john    54
1   mike    34
2   suz     56
3   tin     78
4   yan     31

Example Code

import pandas as pd
data1 = {'trash1': ['john', 'mike', 'suz', 'tin', 'yan'], 
         'trash2': [54, 34, 56, 78, 31], 
         'name': None, 'age': None}
df = pd.DataFrame(data1)
like image 162
Panda Kim Avatar answered Dec 08 '25 20:12

Panda Kim


You can slice with iloc and rename with set_axis:

N = 2
out = (df.iloc[:, :-N]
         .set_axis(df.columns[N:], axis=1)
      )

Output:

   name  age
0  john   54
1  mike   34
2   suz   56
3   tin   78
4   yan   31

Timing of answers for a generalized number of columns:

Overall manually setting the name is reliably the fastest since the data is fully untouched, independently of the number of columns. The nice pop trick becomes very greedy after a threshold. Some of the approaches like shift+drop additionally cause the DataFrame to become fragmented

enter image description here

like image 30
mozway Avatar answered Dec 08 '25 20:12

mozway