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

Pandas rename selected columns with sequential numbers

I have a df with a number or columns, I would like to rename these with incremental numbers selecting the starting and ending range.

enter image description here

With the above image, I would like to select only columns B-D, and rename them to 1-4. So the resulting data frame would be:

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

enter image description here

So basically selecting the headers via index numbers and adding incremental numbers instead.

EDIT: The above dataframe

data = [['a','b','c','d','e','f'], ['a','b','c','d','e','f'], ['a','b','c','d','e','f'],['a','b','c','d','e','f']]

df = pd.DataFrame(data, columns = ['A','B','C','D','E','F'])

>Solution :

Use rename with selected columns by DataFrame.loc – here between B and E:

c = df.loc[:, 'B':'E'].columns
df = df.rename(columns=dict(zip(c, range(1, len(c) + 1))))
print (df)
   A  1  2  3  4  F
0  a  b  c  d  e  f
1  a  b  c  d  e  f
2  a  b  c  d  e  f
3  a  b  c  d  e  f
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