Home > other >  Combine a variable and a string for naming a column in pandas
Combine a variable and a string for naming a column in pandas

Time:10-05

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:

vars = [1, 2, 3]

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

What is the correct way to do it?

CodePudding user response:

Have you considered using f-strings?

vars = [1, 2, 3]

for i in vars:
    df.loc[:, f'col_{i}']
  • Related