Paul
Paul

Reputation: 59

automatically rename columns in pandas based on two indices in loops

I want to automatically rename the column names of a dataframe in pandas using two loops. The indices name should include "C" + "a number between 1 and m" + "a number between 1 and n".

For example, I want to rename 12 columns of a dataframe to C11, C12, C13, C14, C21, C22, C23, C24, C31, C32, C33, and C34.

For that reason I used the following code:

m = 3
n= 4    
df.columns=["C"+str(i) for i in range(1, m)+ str(j) for j in range(1, n)]

But I get the following error

NameError: name 'j' is not defined

This code works for only one loop but not two loops. How I can fix this?

Upvotes: 0

Views: 92

Answers (1)

ArchAngelPwn
ArchAngelPwn

Reputation: 3046

You can use a nested for loop that in range that will give the desired results

m = 3
n= 4  
lst = [f"C{num}{num2}" for num in range(1, m + 1) for num2 in range(1, n + 1)]

You use a +1 in the for loop because range is non-inclusive

Upvotes: 1

Related Questions