Home > database >  Loop Append String creating too many additional DataFrame columns
Loop Append String creating too many additional DataFrame columns

Time:08-24

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.

CodePudding user response:

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.

  • Related