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

Combine a variable and a string for naming a column in pandas

I have a dataframe with several column which have similar names, something like col_1, col_2, col_3.

I am trying to create a for loop to go over the 3 columns and want to use .loc inside the loop to slice the dataframe.

Something like this:

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

vars = [1, 2, 3]

for i in vars:
    df.loc[:, ('col_'+ i):]

What is the correct way to do it?

>Solution :

Have you considered using f-strings?

vars = [1, 2, 3]

for i in vars:
    df.loc[:, f'col_{i}']
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