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

Loop + Append String creating too many additional DataFrame columns

Here is my code, I’m trying to change the column names after I subtract the values in one DataFrame from another, but it’s just creating the incorrect column names.

colnames_in = ['One', 'Two', 'Three', 'Four', 'Five']

for i in range(len(colnames_in)):
    colnames_out = 'new col ' + colnames_in[i]
    df[colnames_out[i]] = df_a[colnames_in[i]] - df_b[colnames_in[I]]

Instead of having "new col One", "new col Two" I’ll just get "n", "e", "w" as the col names.

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

>Solution :

You have at least two errors in your code sample. Both are in the final line.
Here’s a fixed version that should work.

colnames_in = ['One', 'Two', 'Three', 'Four', 'Five']

for i in range(len(colnames_in)):
    colnames_out = 'new col ' + colnames_in[i]
    df[colnames_out] = df_a[colnames_in[i]] - df_b[colnames_in[i]]

If you want to make the for-loop a little more compactt. Try this…

colnames_in = ['One', 'Two', 'Three', 'Four', 'Five']

for cname in colnames_in:
    colnames_out = 'new col ' + cname
    df[colnames_out] = df_a[cname] - df_b[cname]

If you want to perform this process more "Pythonically", check out this previous SO question/answer.

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