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.
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)
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
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

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With