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

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:

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

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?

>Solution :

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

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