Loop + Append String creating too many additional DataFrame columns

Question:

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.

Asked By: Blake S

||

Answers:

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 compact. 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.

Answered By: Juancheeto
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.