'Access columns of a dataframe based on column names using a 'for' loop

Let's say I have data frame consisting of column names M1out1, M1out2, ..., M1out120, 0, 1, ..., 120.

Is there a way in which I can access the columns based on these names using a for loop?

Like for i in range(M1out1, M1out120, 1) , for columns M1out1 through M1out120.



Solution 1:[1]

You can create a slice of the dataframe by a range of columns, and get the list of columns names for that slice:

for col in df.loc[:, 'M1out0':'M1out15'].columns:
    print(col)

Output:

M1out0
M1out1
M1out2
M1out3
M1out4
M1out5
M1out6
M1out7
M1out8
M1out9
M1out10
M1out11
M1out12
M1out13
M1out14
M1out15

Convenience function

def col_range(df, start=None, stop=None, step=None):
    return df.loc[:, start:stop:step].columns

Usage:

# Loop over every 3rd column starting from M1out0 and ending with M1out20:
for col in col_range(df, 'M1out0', 'M1out20', 3):
    print(col)

Output:

M1out0
M1out3
M1out6
M1out9
M1out12
M1out15
M1out18

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 richardec