Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to increment by one the colum names (header) of a dataframe

I have this kind of dataframe

     0    1    2
0  aaa  ddd  ggg
1  bbb  eee  hhh
2  ccc  fff  iii

And I’m trying to have this :

     1    2    3
0  aaa  ddd  ggg
1  bbb  eee  hhh
2  ccc  fff  iii

With pandas.DataFrame.add_prefix, unfortunately, I’m not getting the expected output :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

print(df.add_prefix(+1))
    10   11   12
0  aaa  ddd  ggg
1  bbb  eee  hhh
2  ccc  fff  iii

My question might be silly but do you know how to do that with pandas, please ?

Here is the initial dataframe used :

df = pd.DataFrame({0: ['aaa', 'bbb', 'ccc'], 1: ['ddd', 'eee', 'fff'], 2: ['ggg', 'hhh', 'iii']})

A small detail : The real dataset has hundreds of columns named (0, 1, 2, ….)

>Solution :

You can simply increment by one. An Index behaves like a Series in this respect.

df.columns += 1

Result:

     1    2    3
0  aaa  ddd  ggg
1  bbb  eee  hhh
2  ccc  fff  iii
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading